Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

share|improve this question
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™. 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" –  Gilles Nov 28 '12 at 23:38
show 1 more comment

2 Answers

What jw013 says sounds right to me too. However 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"
  • will work on some shells where previous doesn't, such as BusyBox ash: "'${var//'/'\\''}'"
  • most portable? printf '%s\n' "$var" | sed "s/'/'\\\\''/g; 1s/^/'/; \$s/$/'/"

Improvements gladly welcomed!

share|improve this answer
add comment

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
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.