0

I have noticed a weird behavior when a backtick is used in the beginning of line in bash scripts.

  • example 1:

    echo "Test"
    `ls`
    

    Output:

    Test
    

    and ls is ignored.

  • example 2:

    `test ':";`|)%$kasdj`
    

    This should return an error but it doesn't , it acts like a comment.

New contributor
user7864052 is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
1
  • 1
    Get access to the HTML version of POSIX, or your local manual pages my friend! See my answer below.
    – DannyNiu
    Jun 23 at 1:58

1 Answer 1

3

The

`ls`

in your first script fragment substitutes the command with the output of ls and executes it. If it's an empty directory, then nothing is substituted and nothing happens.

In your second example, the number of backticks is odd not even. So there's a syntax error.

1
  • 2
    More precisely, in sh / bash, `ls` runs the command whose arguments (and the command name is derived from the first) is the result of split+glob applied to the output of ls stripped of its trailing newline characters. For instance, if ls outputs * *<newline> because there's a file named * * in the current directory and $IFS is the default, * * would be split into * and * and each * expanded to the non-hidden files in the current directory, so would try to run the equivalent of '* *' '* *' Jun 23 at 5:18

Your Answer

user7864052 is a new contributor. Be nice, and check out our Code of Conduct.

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.