Score:-2

Can I get an explanation on escaping shell variables?

au flag
j0h

I have a C program I am integrating into a shell script. There is a line that gets the time of birth for $HOME using system("stat $HOME | awk 'FNR == 8 {print}' | awk '{print $2}'"); and it works great in C. when I echo that line to bash with:

echo system(\"stat $HOME | awk 'FNR == 8 {print}' | awk '{print $2}'\");>> file.c

the second awk pipe doesn't happen. so instead of getting: 2021-04-11

I get: Birth: 2021-04-11 18:28:25.373220337 -0400

I don't understand the issue here. I checked the resulting C code, and its missing $2 which is why the 2nd awk function fails. ok, so I escaped the with \$2 but I don't understand why I needed to. I didn't escape the other shell variable $HOME and that works fine.

hr flag
Presumably it "works fine" when you don't escape `$HOME` because you're executing the resulting program in the same environment that you're generating it in - so it doesn't matter whether `$HOME` is expanded by the current shell or by the shell invoked by the `system` call. FYI you can probably save a lot of headaches by using a [quoted here-doc](https://stackoverflow.com/a/47436574/4440445) to construct your code, rather than an `echo` command.
Score:3
br flag

All $ are interpreted as a variable by the shell (bash) inside ". They need to be escaped.

Additionally, the ( are interpreted by the shell, which needs a complete quoting of the string.

echo "system(\"stat \$HOME | awk 'FNR == 8 {print}' | awk '{print \$2}'\")" >> file.c

Besides this, you will get a problem as soon as $HOME has a space inside.

Reminder: There are better ways in bash and in C to get the needed information.

e.g. for bash:

date -d "$( stat -c %w "$HOME" )" +%F
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.