By user775187

2011-06-26 05:49:21 8 Comments

I need to check the existence of an input argument. I have the following script

if [ "$1" -gt "-1" ]
  then echo hi

I get

[: : integer expression expected

How do I check the input argument1 first to see if it exists?


@phoxis 2011-06-26 05:55:41

It is:

if [ $# -eq 0 ]
    echo "No arguments supplied"

The $# variable will tell you the number of input arguments the script was passed.

Or you can check if an argument is an empty string or not like:

if [ -z "$1" ]
    echo "No argument supplied"

The -z switch will test if the expansion of "$1" is a null string or not. If it is a null string then the body is executed.

@J. M. Becker 2012-06-02 20:38:13

I like to do it this way, in terse syntax and still POSIX acceptable. [ -z "$1" ] && echo "No argument supplied" I prefer one-liners, as they are easier for me; and it's also faster to check exit value, compared to using if

@msanford 2013-02-05 16:37:56

You probably want to add an exit 1 at the end of your echos inside the if block when the argument is required for the script to function. Obvious, but worth noting for completeness.

@tripleee 2013-05-06 04:40:38

It is possible, though rarely useful, for the first argument to be initialized but empty; programname "" secondarg third. The $# check unambiguously checks the number of arguments.

@HighOnMeat 2013-09-13 07:17:34

For a noob, especially someone who comes from a non-scripting background, it is also important to mention some peculiarities about these things. You could have also mentioned that we need a space after the opening and the closing brace. Otherwise things do not work. I am myself a scripting noob (I come from C background) and found it the hard way. It was only when I decided to copy the entire thing "as is" that things worked for me. It was then I realized I had to leave a space after the opening brace and before the closing one.

@gcb 2014-02-26 23:18:32

and for optional args if [ ! -z "$1" ]; then ...

@Matthias 2016-05-17 11:08:35

@HighOnMeat the reason that is not mentioned is because it would have to be mentioned in each and every place where an if statement is used. And that would just be too much. However, people such as yourself commenting like this is just excellent, as you can see, it looks like you have helped 4 people to learn this.

@Flimm 2016-12-08 09:45:55

I like to echo error messages to stderr: echo "No argument supplied" >&2

@phoxis 2016-12-08 16:08:18

@Flimm, naturally, this is just a demonstration.

@Jon R. 2017-08-15 16:06:52

I was hung on this for a bit. Please note that the space after [ and before ] are crucial. if [$# -eq 0] will not work, but if [ $# -eq 0 ] will.

@anass 2018-01-15 17:04:49

Hello! I'm trying to check if the argument passed to my script is equal to "var1" and "var2" so I did the flowing but it's not working: if [[ $1 -ne 'var1' || $1 -ne 'var2' ]] then echo "bad argument" fi

@Alex Hall 2019-12-04 12:07:25

@anass this is a very late reply, but I started picking apart your question, and there are enough problems in it that you need to just post a new question on SO. It might also help if your question states what you're generally trying to accomplish. Feel free to do so and post a link to it as a reply comment.

@fiorentinoing 2019-12-17 11:28:00

I prefer oneliners too [ -z "${1// }" ] && echo "No argument supplied"

@Colm Bhandal 2020-05-18 12:35:33

@J.M.Becker I tried your one liner but got the error: $1: unbound variable. For me the accepted answer is safer.

@J. M. Becker 2020-05-19 21:07:42

@ColmBhandal, you have set options that will trigger that responce on an unset var, you'd need to use "${1:-}" instead of just the plain "$1".

@TRiG 2020-06-11 11:45:12

@Skaldebane I've turned off the code colouring again, since it was incorrectly marking non-comments as comments. No colouring is much to be preferred to inaccurate colouring.

@Skaldebane 2020-06-17 13:27:14

@TRiG Oh yeah I didn't notice that... Thanks for informing!

@AndrewD 2020-01-26 20:03:00

one liner bash function validation

myFunction() {

    : ${1?"forgot to supply an argument"}
    if [ "$1" -gt "-1" ]; then
        echo hi


add function name and usage

myFunction() {

    : ${1?"forgot to supply an argument ${FUNCNAME[0]}() Usage:  ${FUNCNAME[0]} some_integer"}
    if [ "$1" -gt "-1" ]; then
        echo hi


add validation to check if integer

to add additional validation, for example to check to see if the argument passed is an integer, modify the validation one liner to call a validation function:

: ${1?"forgot to supply an argument ${FUNCNAME[0]}() Usage:  ${FUNCNAME[0]} some_integer"} && validateIntegers $1 || die "Must supply an integer!"

then, construct a validation function that validates the argument, returning 0 on success, 1 on failure and a die function that aborts script on failure

validateIntegers() {

    if ! [[ "$1" =~ ^[0-9]+$ ]]; then
        return 1 # failure
    return 0 #success


die() { echo "$*" 1>&2 ; exit 1; }

Even simpler - just use set -u

set -u makes sure that every referenced variable is set when its used, so just set it and forget it

myFunction() {
    set -u
    if [ "$1" -gt "-1" ]; then
        echo hi


@Val 2013-11-13 19:25:17

It is better to demonstrate this way

if [[ $# -eq 0 ]] ; then
    echo 'some message'
    exit 1

You normally need to exit if you have too few arguments.

@dshepherd 2015-11-26 11:22:29

No it isn't: this has exit 1 which you usually want, and uses the [[ ]] test which (iirc) is usually more reasonable. So for people blindly copy-pasting code this is the better answer.

@Sebastián Grignoli 2016-02-03 19:31:21

To know more about the difference between [ ] and [[ ]] see…

@Aleks N. 2014-07-31 18:55:11

In some cases you need to check whether the user passed an argument to the script and if not, fall back to a default value. Like in the script below:

emulator @$1 -scale $scale

Here if the user hasn't passed scale as a 2nd parameter, I launch Android emulator with -scale 1 by default. ${varname:-word} is an expansion operator. There are other expansion operators as well:

  • ${varname:=word} which sets the undefined varname instead of returning the word value;
  • ${varname:?message} which either returns varname if it's defined and is not null or prints the message and aborts the script (like the first example);
  • ${varname:+word} which returns word only if varname is defined and is not null; returns null otherwise.

@Eki 2017-03-02 16:52:08

The example above seems to use ${varname?message}. Is the extra : a typo, or does it change behavior?

@user.friendly 2017-08-16 03:29:45

Eki, the ":" is a builtin command and shorthand for /bin/true in this example. It represents a do-nothing command that basically ignores the arguments it is provided. It is essential in this test in order to keep the interpreter from trying to execute the contents of "$varname" (which you certainly do NOT want to happen). Also worth noting; you can test as many variables with this method as you wish. And all with specific error messages. i.e. : ${1?"First argument is null"} ${2?"Please provide more than 1 argument"}

@seorphates 2018-08-02 21:00:31

Only because there's a more base point to point out I'll add that you can simply test your string is null:

if [ "$1" ]; then
  echo yes
  echo no

Likewise if you're expecting arg count just test your last:

if [ "$3" ]; then
  echo has args correct or not
  echo fixme

and so on with any arg or var

@f2cx 2017-12-29 17:55:39

I often use this snippet for simple scripts:


if [ -z "$1" ]; then
    echo -e "\nPlease call '$0 <argument>' to run this command!\n"
    exit 1

@Danijel 2018-10-30 14:52:39

So, this is to be used in you need only one argument?

@Brad Parks 2017-09-13 16:45:19

If you'd like to check if the argument exists, you can check if the # of arguments is greater than or equal to your target argument number.

The following script demonstrates how this works

#!/usr/bin/env bash

if [ $# -ge 3 ]
  echo script has at least 3 arguments

produces the following output

$ ./
$ ./ 1
$ ./ 1 2
$ ./ 1 2 3
script has at least 3 arguments
$ ./ 1 2 3 4
script has at least 3 arguments

@devnull 2013-07-20 10:26:07

Another way to detect if arguments were passed to the script:

((!$#)) && echo No arguments supplied!

Note that (( expr )) causes the expression to be evaluated as per rules of Shell Arithmetic.

In order to exit in the absence of any arguments, one can say:

((!$#)) && echo No arguments supplied! && exit 1

Another (analogous) way to say the above would be:

let $# || echo No arguments supplied

let $# || { echo No arguments supplied; exit 1; }  # Exit if no arguments!

help let says:

let: let arg [arg ...]

  Evaluate arithmetic expressions.


  Exit Status:
  If the last ARG evaluates to 0, let returns 1; let returns 0 otherwise.

@user.friendly 2017-08-16 03:42:22

-1 this might be the worst method if validating existence of an argument.. plus it can trigger history substitution and potentially do bad things.

@Timo 2017-12-19 11:53:47

instead of exit which kills my zsh process, I use return which does not kill it

@Zhro 2019-09-25 04:30:47

Why would ((!$#)) trigger history substitution?

@Ranjithkumar T 2013-10-21 04:20:39


 if [ "$#" -eq  "0" ]
     echo "No arguments supplied"
     echo "Hello world"

@user13107 2014-12-12 03:00:49

Why do you need double-quotes for $# and 0?

@Ranjithkumar T 2014-12-15 07:15:52

No problem if we use without double-quotes as like $# and 0

@Lajos Meszaros 2015-06-11 14:56:40

on windows, mingw this is the only way to go.

@Chris K 2015-07-30 22:46:09

This answer provides great starting point for a script I just made. Thanks for showing the else, too.

@Dennis 2016-01-31 20:21:53

@user13107 double quoted variables in bash prevent globbing (i.e. expanding filenames like foo*) and word splitting (i.e. splitting the contents if the value contains whitespace). In this case it's not necessary to quote $# because both of those cases do not apply. Quoting the 0 is also not necessary, but some people prefer to quote values since they are really strings and that makes it more explicit.

@Cwissy 2013-10-24 22:39:19

As a small reminder, the numeric test operators in Bash only work on integers (-eq, -lt, -ge, etc.)

I like to ensure my $vars are ints by

var=$(( var + 0 ))

before I test them, just to defend against the "[: integer arg required" error.

@user.friendly 2017-08-16 03:56:19

Neat trick, but please note: due to bash's inability to handle floats in arithmetic, this method can cause a syntax error and return non-zero which would be a hindrance where errexit is enabled. var=$(printf "%.0f" "$var") can handle floats but suffers from the non-zero exit when given a string. If you don't mind an awk, this method I use seems to be the most robust for enforcing an integer: var=$(<<<"$var" awk '{printf "%.0f", $0}'). If var is unset, it defaults to "0". If var is a float, it is rounded to the nearest integer. Negative values are also fine to use.

Related Questions

Sponsored Content

67 Answered Questions

[SOLVED] How to get the source directory of a Bash script from within the script itself?

  • 2008-09-12 20:39:56
  • Jiaaro
  • 1753318 View
  • 5033 Score
  • 67 Answer
  • Tags:   bash directory

37 Answered Questions

[SOLVED] How can I check if a program exists from a Bash script?

  • 2009-02-26 21:52:49
  • gregh
  • 707966 View
  • 2258 Score
  • 37 Answer
  • Tags:   bash

13 Answered Questions

[SOLVED] How to echo shell commands as they are executed

33 Answered Questions

[SOLVED] How to check if a variable is set in Bash?

  • 2010-08-30 14:54:38
  • prosseek
  • 1362189 View
  • 1606 Score
  • 33 Answer
  • Tags:   bash shell variables

20 Answered Questions

[SOLVED] How do I tell if a regular file does not exist in Bash?

  • 2009-03-12 14:48:43
  • Bill the Lizard
  • 2544359 View
  • 3301 Score
  • 20 Answer
  • Tags:   bash file-io scripting

31 Answered Questions

[SOLVED] How do I prompt for Yes/No/Cancel input in a Linux shell script?

26 Answered Questions

[SOLVED] How to check if a string contains a substring in Bash

35 Answered Questions

[SOLVED] How can I check if a directory exists in a Bash shell script?

  • 2008-09-12 20:06:25
  • Grundlefleck
  • 2817510 View
  • 3765 Score
  • 35 Answer
  • Tags:   bash shell unix posix

14 Answered Questions

[SOLVED] How do I set a variable to the output of a command in Bash?

32 Answered Questions

[SOLVED] How do I split a string on a delimiter in Bash?

Sponsored Content