Skip to main content
We’ve updated our Terms of Service. A new AI Addendum clarifies how Stack Overflow utilizes AI interactions.

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

16
  • 95
    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 Commented Jun 2, 2012 at 20:38
  • 225
    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. Commented Feb 5, 2013 at 16:37
  • 29
    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. Commented May 6, 2013 at 4:40
  • 65
    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. Commented Sep 13, 2013 at 7:17
  • 112
    and for optional args if [ ! -z "$1" ]; then ... Commented Feb 26, 2014 at 23:18