0

I am just learning the (very) basics of BASH.

while IFS= read -r line; do
...
done

The above is helpful when needing to skip commented (say by #) lines from a file. One particular implementation of the above I come across does this, however I don't understand it. The person who posted it didn't provide any explanation for the commands (maybe they are very simple indeed). I kept searching and found not-so-cryptic solutions, but I believe it shall be very good me to understand the following:

while read -r line; do
[[ $line = \#* ]] && continue
done < "$file"

My intuition is that $line = \#* is checking the content of variable line and if it starts with # (# is a special character, thus needs \), does something. The * is there to signify that anything might appear after the initial #. Just as in $rm -r *.pdf say.

But why the [] ? And why double [ [] ] ?

Also, just to check: is BASH a combination of python and c++ in terms of code arrangement? Every instruction shall start of a new line, however if we want to have 2 instructions in row on the same line, they need to be delimited by a ; (thus emulating c/c++)? Thus the ... line; do instructions?

Thank you!

velenos14
  • 534
  • 4
  • 13
  • 1
    Should be `[[` and `]]`, no spaces. – Shawn Feb 18 '21 at 08:05
  • 1
    Documented at https://www.gnu.org/software/bash/manual/html_node/Conditional-Constructs.html – Shawn Feb 18 '21 at 08:07
  • @Shawn, edited it now ! – velenos14 Feb 18 '21 at 08:07
  • 1
    I wouldn't think of bash in terms of python and c++, it's very different from either. But you're right about `;` functioning a lot like a line break. Two things that throw people new to shell scripting: spaces are important delimiters, don't add or remove them unless you know what you're doing; and shell syntax is *extremely* context-dependent (e.g. what `5 + 3` means depends completely on where it occurs). – Gordon Davisson Feb 18 '21 at 08:12
  • 1
    @velenos14 : `[[ .... ]]` is a syntactic construct to evaluate certain kinds of condition, and set the exit code to 0 or 1, depending on whether they are met or not. You find this documented in the bash man-page in the section _CONDITIONAL EXPRESSIONS_. – user1934428 Feb 18 '21 at 08:24
  • 1
    @velenos14 : bash has several separators for separating commands, for instance `;`, `&&`, `||`, `&`, with different semantics. The _newline_ is just an equivalent to the `;` separator. – user1934428 Feb 18 '21 at 08:27
  • Neither Python nor C++ are very good analogies to how the syntax of the shell works. Probably read the man page about how each input line is evaluated. – tripleee Feb 18 '21 at 08:31

0 Answers0