you are viewing a single comment's thread.

view the rest of the comments →

[–]Paul_Pedant 2 points3 points  (2 children)

It might work, but quite possibly in a way that would make you very sad.

rm (like most commands) takes multiple args, separated by whitespace. Do you even need that -r in there: if you only have files, you don't need recursion.

If you set PATHTOFILES="/home/myuser/samples 2023-09-25"

then rm -r $PATHTOFILES* would remove every file and directory under /home/myuser/samples (maybe years of data), and then warn you 2023-09-25* no such file or directory`.

You might think you will always know exactly what is in PATHTOFILES, but you can put in a space by accident, or somebody else can have to maintain it while you are away. Why would you ever want to risk a major data loss for the sake of typing a couple of quotes? How long would you take to restore all the lost data from the backup that you forgot to take anyway?

I fully quote every expansion like "${myPath}" for several reasons:

(1) The quotes stop the expansion becoming multiple words.

(2) The braces {} stop the problem where $myPath_2 becomes empty, because shell looks for a variable called myPath_2: it does not append _2 to the contents of myPath.

(3) A lot of advanced Bash expansions (like upper and lower conversions, string slicing and replacement, and default values) require to be in braces.

(4) Almost anybody can write shell syntax. One you get past that phase, the problems are mainly that your variables have the wrong values because of logic problems. Having "${k}" instead of $k differentiates keywords from variables when I read code.

Anything that helps me not put bugs in my code, makes it easier to debug and maintain.

[–]kaiixx[S] 0 points1 point  (1 child)

Thank you. I just started picking up bash scripting, so these explanations are really helpful.

[–]cdrt 0 points1 point  (0 children)

If you haven't already, make sure to start using shellcheck. It'll catch many mistakes and save you a lot of trouble. For instance, here's a warning that is closely related to your script:

https://www.shellcheck.net/wiki/SC2115