1

I have a bash script like this with a function

_launch()
{
  ${1}
}

testx()
{
  _launch "TESTX=1 ls -la"
}

testx

I get error "TESTX=1 command not found" in _launch function. Why? When I run TESTX=1 ls -la directly on shell it works fine.

2
  • 1
    Why are you doing this? Why can't you pass the value of TESTX as a separate argument? Commented Feb 26, 2019 at 4:45
  • I want to launch an app with variable value set. ls -la is just an example Commented Feb 26, 2019 at 4:48

2 Answers 2

2

It's not a good idea to use variables to hold commands. See BashFAQ/050

As long as you are dealing with executables and not shell built-ins, you could do this:

_launch() {
    env $1
}

This won't play well in case you have literal spaces in values used in var=value pairs or arguments to the command being launched.

You can overcome this problem by just passing the command to the launch function and setting your variables in function invocation itself, like this:

_launch() {
    #       your launch prep steps here...
    "$@"  # run the command
    #       post launch code here
}
TESTX=1 TESTY=2 TESTZ=3 _launch ls -la

The variables would be passed down to the launched command as environment variables.

Sign up to request clarification or add additional context in comments.

Comments

0

You get the error because first looks at the statement to see whether we have a variable assignment, and then does parameter expansion. In your case, bash doesn't recognize that you want to extend the environment for your ls command, and treats TESTX=1 as command to be executed.

For the same reason, the following does not set the bash variable ABC:

x='ABC=55'
$x

This would print ABC=55: command not found.

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.