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.

1
  • 1
    Get access to the HTML version of POSIX, or your local manual pages my friend! See my answer below.
    – DannyNiu
    Jun 23, 2022 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, 2022 at 5:18

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .