1

In my environment:

THE_KEY="Bearer ABCDEFGHI"

and here is some_script.sh

#!/bin/sh
./yet_other_script.sh "$(echo $THE_KEY)"

which calls yet_other_script.sh such that parameter $1 is Bearer ABCDEFGHI

Is there a simpler way than "$(echo $THE_KEY)"?

2 Answers 2

2

Replace:

./yet_other_script.sh "$(echo $THE_KEY)"

with:

./yet_other_script.sh "$THE_KEY"

More details

Consider a directory with these files:

$ ls file*
file  file1  file2  file3

Define the variable:

$ TheKey="a    file?"

Now, watch what echo $TheKey does:

$ echo $TheKey
a file1 file2 file3

The multiple spaces between a and file have been collapsed. This is the result of word splitting. Also, the string has been subjected to pathname expansion resulting in file? being replaced by the names of files.

In sum, unless you explicitly want the shell to perform expansions, always put your shell variables in double-quotes:

$ echo "$TheKey"
a    file?

That's not all: Command substitution removes trailing newlines from the output of the command. For example:

$ TheKey=$'abc\n\n\n'
$ echo "$(echo "$TheKey")"
abc
$ 
Sign up to request clarification or add additional context in comments.

Comments

2

There are many ways to pass a value from one script to another:

  1. As a parameter: ./script.sh "$key" - the value is available as $1 within script.sh.
  2. On standard input: echo "$key" | ./script.sh - the value can be read for example using the read built-in command.
  3. As an exported variable:

    export KEY
    ./script.sh
    

    $KEY is then available with the same name in script.sh.

  4. Passing an indirect reference such as a filename where the value or even the assignment (key=value) is stored.

The naming conventions are intentional: by convention upper case names should only be used for exported variables.

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.