Suppose that I've got the following script called test.sh:

#! /bin/sh -
printf '%s\n' "${1:?empty or missing argument}"

When run without any command-line arguments it behaves like this:

$ ./test.sh
./test.sh: 2: ./test.sh: 1: empty or missing argument

Question: Is it possible to change the "./test.sh: 2:" part of the error message?

  • 4
    Note that ${1:?missing argument} would not check whether $1 is missing but if it's empty (and the script could be given one empty argument). For missing, you'd need ${1?missing argument} instead. In any case, if you care about the format, you might as well do it the long way like with if [ "$#" -eq 0 ]; then... (missing) or if [ -z "$1" ] (empty). – Stéphane Chazelas Aug 21 '17 at 22:02
  • 1
    @jimmij From what I read it is perfectly ok to put a space after #!. (For example in the book Classic Shell Scripting chapter 2.4 and here unix.stackexchange.com/q/276751/128489.) – Mateusz Piotrowski Aug 21 '17 at 23:02

The answer to your question is 'no'; using that syntax shall output the script, line number, and variable referenced to standard error as you describe. If you want to alter this, pipe standard error into a process to massage it into your desired format in a script which itself runs the script outputting the error message.

  • 1
    Why is the script name mentioned twice in the message? – Mateusz Piotrowski Aug 21 '17 at 22:43
  • 1
    Unable to replicate this. stderr of ./se.sh: line 2: 1: whoops with a script containing a shebang line and output statement. – DopeGhoti Aug 21 '17 at 23:01
  • I'm on Ubuntu so my /bin/sh is probably Dash. I experience the same behaviour as you do when I use Bash instead. – Mateusz Piotrowski Aug 21 '17 at 23:05
  • 1
    A sound hypothesis; I tested on the sh that comes with McBSD. – DopeGhoti Aug 21 '17 at 23:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.