Bash Script Append Variable to File

Bash Script Append Variable to File

I just created bash script and want to append the variable script, but it was not working properly, and here is the script :

export PROMPT_COMMAND='RETRN_VAL=$?;logger -p local6.debug "$(whoami) [$$]: $(history 1 | sed "s/^[ ]*[0-9]\+[ ]*//" ) [$RETRN_VAL]"'

I tried to run append this script using echo but the results is not the same:

echo "export PROMPT_COMMAND='RETRN_VAL=$?;logger -p local6.debug "$(whoami) [$$]: $(history 1 | sed "s/^[ ]*[0-9]\+[ ]*//" ) [$RETRN_VAL]"'" > wew.txt

if we cat wew.txt the result was :

export PROMPT_COMMAND='RETRN_VAL=0;logger -p local6.debug widianto [69]: echo "export PROMPT_COMMAND='RETRN_VAL=$?;logger -p local6.debug "$(whoami) [$$]: $(history 1 | sed "s/^[ ]*[0-9]\+[ ]*//" ) [$RETRN_VAL]"'" > wew.txt []'

Thanks for your help

0

2 Answers

What you're observing here is that 'strong quotes' lose their strength when wrapped in "weak quotes":

$ echo $foo
bar
$ echo '$foo'
$foo
$ echo "echo '$foo'"
echo 'bar'

Although you could fix your code by backslash-escaping every special character, a better way to avoid expansion by the shell might be to use a here-document instead of an echo, and quote (in any of the supported ways - weak, strong or backslash) the end marker:

$ cat << \EOF
export PROMPT_COMMAND='RETRN_VAL=$?;logger -p local6.debug "$(whoami) [$$]: $(history 1 | sed "s/^[ ]*[0-9]\+[ ]*//" ) [$RETRN_VAL]"'
EOF

export PROMPT_COMMAND='RETRN_VAL=$?;logger -p local6.debug "$(whoami) [$$]: $(history 1 | sed "s/^[ ]*[0-9]\+[ ]*//" ) [$RETRN_VAL]"'
0

I have succesfully with created variable :

widianto@rancher3:~$ cat b.bash
#!/bin/bash
# widianto

a="export PROMPT_COMMAND='RETRN_VAL=$?;logger -p local6.debug"
b='"$(whoami) [$$]: $(history 1 | sed'
c='"s/^[ ]*[0-9]\+[ ]*//" ) [$RETRN_VAL]"'


echo "$a $b $c'" >> /home/widianto/test.txt

Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

David Miller
Author

David Miller

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.