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?

mtk
  • 26,802
  • 35
  • 91
  • 130
  • 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 '12 at 14:54
  • 3
    I suggest a quick `set -x` so you can see what's actually being executed. – derobert Nov 28 '12 at 16:55
  • 2
    You should [Use More Quotes™](http://mywiki.wooledge.org/BashGuide/Practices/#Quoting). Escaping leads to way more complicated code. – l0b0 Nov 28 '12 at 18:41
  • As @l0b0 indirectly suggests, do you get better results with `loadPatch -name "$1"` – glenn jackman Nov 28 '12 at 19:54
  • 2
    Did you edit the script on a Windows machine? [Script failing with "command not found: ^M"](http://unix.stackexchange.com/q/47280) – Gilles 'SO- stop being evil' Nov 28 '12 at 23:38
  • @l0b0 the quoting didn't solved the problem. I envisage it's some other problem, might be with the binary prog I am using... So, currently just going with a hard coded way. Thanks for the help. – mtk Nov 29 '12 at 07:11

2 Answers2

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!

dubiousjim
  • 2,648
  • 19
  • 27
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
Chad Clark
  • 316
  • 1
  • 4