1

I am trying to automate some of my stuff and facing a issue, the problem boils down to escaping the value that is being passed as a argument to the script.

myScript.sh

#!/bin/bash

loadPatch -name $1

where $1 is the first argument and can have value like 'p12.9.5-bug34'

Running it as

myScript p12.9.5-bug34

produces no result. I checked with echo $? the output was successful, but the required operation didn't happen.

I replaced $1 with this actual value to test in the script and it worked as expected. There is no way for me to put a print statement in loadPatch to verify what arguments it has received.

So, I envisage there is some escaping problem here and hence need to know, is there any function/utility which I could use to escape the argument before using?

Please let me know if you see any other error with this?

6
  • 4
    p12.9.5-bug34 is a completely harmless name and should work fine despite the lack of quoting "$1". Your problem must be somewhere else.
    – jw013
    Nov 28, 2012 at 14:54
  • 3
    I suggest a quick set -x so you can see what's actually being executed.
    – derobert
    Nov 28, 2012 at 16:55
  • 2
    You should Use More Quotes™. Escaping leads to way more complicated code.
    – l0b0
    Nov 28, 2012 at 18:41
  • As @l0b0 indirectly suggests, do you get better results with loadPatch -name "$1" Nov 28, 2012 at 19:54
  • 2
    Did you edit the script on a Windows machine? Script failing with "command not found: ^M" Nov 28, 2012 at 23:38

2 Answers 2

4

To answer the question asked, because others may search for this title:

  • zsh only: print -r -- ${(q)var} ${(qq)var} ${(qqq)var} ${(qqqq)var} for different types of quoting.
  • ksh93, zsh, or bash: printf %q "$var"
  • BusyBox (and all above).

    Use of vars level out differences between ash, bash and ksh:

    q1="'"
    q2="'\''"
    printf '%s\n' "'${var//$q1/$q2}'"
    

    Not in dash and old shells (those missing ${var//pat/str}).

  • most portable?

    printf "'%s'\n" "$(printf '%s' "$var" | sed "s/'/'\\\\''/g")"
    
    Or
    
    printf '%s\n' "$var" | sed "s/'/'\\\\''/g; 1s/^/'/; \$s/$/'/"
    

Improvements gladly welcomed!

0

I agree there should not be a problem with special characters in that filename.

I have found that sometimes scripts are not running in the folder I expected. If you replace "loadPatch -name" with "echo" you can verify $1 is what you expect. If it is what you expect then add these lines to see if the current directory is what you expect:

ls -l $1
pwd

You must log in to answer this question.

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