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
  • 27,530
  • 35
  • 94
  • 130

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,698
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