shell - Sh command with -c option in unix -


i trying run below set of commands using sh -c

sh -c " dup_flag=`wc -l test.dat | awk '{print $1}'`; user='test@domain.com'; text='hi'; subject='notification'; if [ $dup_flag -eq 0 ];   echo $dup_flag | mailx -r $user -s $subject $user; fi " 

it not giving desired result

when run same in script

dup_flag=`wc -l test.dat | awk '{print $1}'` user='user@domain.com' text='hi' subject='notification' if [ $dup_flag -eq 8 ]   echo $dup_flag | mailx -r $user -s $subject $user fi 

it giving desired result

can 1 me doing wrong here .i haven run them sh -c

thanks

the first version fails because double-quoted argument processed shell invokes sh -c "…your script…".

that means wc , awk run before sh -c invoked. also, various variable references $dup_flag etc evaluated invoking shell, not invoked shell.

you'd need use backslashes escape back-ticks , dollar signs. if changed $(…) notation, you'd still have escape $.

or use single quotes around sh -c '…your script…' , use double quotes appropiate inside script.

i thought i'd added 'escapes' , 'single quotes' sections before. submission process glitched (paused); internet connection @ fault, seem have closed tab without noticing not successful.

escapes

sh -c " dup_flag=\`wc -l test.dat | awk '{print \$1}'\`; user='test@domain.com'; subject='notification' if [ \$dup_flag -eq 0 ]   echo \$dup_flag | mailx -r \$user -s \$subject \$user fi " 

single quotes

sh -c ' dup_flag=`wc -l test.dat | awk "{print $1}"` user="test@domain.com" subject="notification" if [ "$dup_flag" -eq 0 ]   echo "$dup_flag" | mailx -r "$user" -s "$subject" "$user" fi ' 

note single-quoted version make easier have multi-word subject lines email, etc.

in both versions, deleted text unused. semicolons aren't necessary when command spread on multiple lines (so removed them). they'd necessary if flattened onto single line.


actually, need run mentioned commands in informatica command task runs commands sh -c " script ".

ouch. adds number of levels of possible confusion. informatica code creates shell command this:

char *args[] = { "sh", "-c", your_string, 0 }; execvp(args[0], args); 

in case, diagnosis of problem off mark; nothing except final shell interprets contents of string.

otoh, use:

char buffer[4096]; snprintf(buffer, sizeof(buffer), "sh -c \"%s\"", your_string); system(buffer); 

in case, system() function runs shell in turn analyzes , runs shell runs script. analysis comes effect.

there other ways achieve job; might have subtly different effects.


Comments