Find the answer to your Linux question:
Results 1 to 4 of 4
I have a line in a shell script that looks like this: Code: running=`ps -p $pid -o args= | sed -n "s?^$php_fpm_BIN\(\ .*\)*\$?&?p"` But this gives an error about an ...
  1. #1
    Just Joined!
    Join Date
    Oct 2010
    Posts
    5

    Confused about escaping in backticks

    I have a line in a shell script that looks like this:
    Code:
    running=`ps -p $pid -o args= | sed -n "s?^$php_fpm_BIN\(\ .*\)*\$?&?p"`
    But this gives an error about an unterminated `s' command. If I double escape the closing $ like
    Code:
    running=`ps -p $pid -o args= | sed -n "s?^$php_fpm_BIN\(\ .*\)*\\$?&?p"`
    then it works.

    Why does the $ need double escaping?

  2. #2
    Just Joined! cfajohnson's Avatar
    Join Date
    May 2007
    Location
    Toronto, Canada
    Posts
    52

    What does $php_fpm_BIN contain?

  3. #3
    Just Joined!
    Join Date
    Oct 2010
    Posts
    5
    Quote Originally Posted by cfajohnson View Post

    What does $php_fpm_BIN contain?
    The path and filename of a binary executable e.g.
    /path/to/php/bin/php_fpm

  4. #4
    Linux User Manko10's Avatar
    Join Date
    Sep 2010
    Posts
    250
    You have to double-escape this because you are passing the dollar sign to an environment, which interprets it. If you write \$, it is interpreted as a raw $ and then passed to the expression in backticks. Therefore, the backtick environment tries to interpret it again.
    To avoid this behavior either use $(…) (which is the newer and recommended way) or use single-quotes for your sed command.

    You can easily check the different behaviors with these commands:
    Code:
    export FOO=bar
    
    echo `echo $FOO`
    echo `echo \$FOO`
    echo `echo "$FOO"`
    echo `echo "\$FOO"`
    echo `echo '$FOO'`
    echo `echo '\$FOO'`
    echo $(echo $FOO)
    echo $(echo \$FOO)
    Refining Linux Advent calendar: “24 Outstanding ZSH Gems

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...