3

I have a bash script that contains the following:

MY_COMMAND="MY_PWD=`pwd`; export MY_PWD; MY_PWD_BASENAME=`basename $MY_PWD`; echo $MY_PWD_BASENAME"; export MY_COMMAND

When I source the script from the terminal, I get the following error:

basename: missing operand
Try `basename --help' for more information.

This indicates that the commands in MY_COMMAND are not executed in sequential order. What is happening here?

3
  • Why do you expect that FOO="cmd1;cmd2" would execute any commands? Commented Jan 26, 2017 at 15:44
  • 5
    Use a function. Do not put commands in a variable. Use a function. Commented Jan 26, 2017 at 15:51
  • @hek2mgl try it and you'll see that it does execute the commands. The question is why it does not execute them sequentially? Commented Jan 26, 2017 at 15:55

1 Answer 1

5

The following line:

MY_COMMAND="MY_PWD=`pwd`; export MY_PWD; MY_PWD_BASENAME=`basename $MY_PWD`; echo $MY_PWD_BASENAME"

will not execute the following commands (as you may think):

MY_PWD=`pwd`
export MY_PWD
MY_PWD_BASENAME=`basename $MY_PWD`
echo $MY_PWD_BASENAME"

Instead it will expand the command substitutions

`pwd`
`basename $MY_PWD`

and replace them with their output. Since $MY_PWD is not set, basename will get executed without the required argument, like:

basename

That leads to the error.


Fix: I recommend to use $() instead of backticks for the command substitution. One benefit is that you can nest them:

MY_COMMAND="MY_PWD=$(pwd); export MY_PWD; MY_PWD_BASENAME=$(basename "$(pwd)"); echo $MY_PWD_BASENAME"

However, that's just the syntax fix. Generally I recommend to use a function like @chepner suggested

lib.sh

function basename_pwd() {
    basename "$(pwd)"
}

Use the function:

#!/bin/bash
source "lib.sh"
basename_pwd
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.