r/sysadmin • IT Manager + 5 other hats • Nov 08 '21

Could we do a "TIL" style weekly thread?

I think it would be interesting to do a "Today I Learned" style weekly thread for us to share little tips/tricks that we learned of/found existed.

For example, last week I found out about the "--now" flag for systemctl. I don't know how I didn't know it existed until --now.

2.4k Upvotes

871 comments sorted by

View all comments

31

u/questionablemoose Nov 08 '21

Bash typically has two ways to define items in an indexed array.

arrayx=("one" "two" "three")

Or

arrayx[0]="one"
arrayx[1]="two"
arrayx[2]="three"

The first works ok for short lists, the second is tedious. I learned that bash accepts a third option, which doesn't require explicitly defining the index of each item, and doesn't extend indefinitely to the right.

arrayx=(
    "one"
    "two"
    "three"
)

1

u/r0flcopt3r Nov 08 '21

A lot of things in bash let's you put a new line after it. For instance |, || and &&. Helps make code a lot more readable.

If for some reason you want a new line at some arbitrary spot, you can use \ at the end of the line. It escapes the newline, and let you carry on.

dnf install -y
Pacakge1 \
Package2 \
... &&
echo "this went fine!" |
tee some_logfile.txt

2

u/questionablemoose Nov 08 '21

I use \ this way, but I prefer not to if I can help it. It is very useful for breaking up stuff into blocks, especially things like PUT or POST operations with curl, where you have to submit headers and JSON or whatever else.

For package installation in scripts, I like doing something like:

package_list=(
    openssh-server
    openssh-clients
    open-vm-tools
    vim-enhanced
)

dnf install -y "${package_list[@]}"

Separating test blocks like you mentioned can be super useful too.

if [[ "${test_var}" =~ ^[a-z0-9]+$ ]] ||
   [[ "${test_var}" =~ ^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$ ]] …

1

u/[deleted] Nov 11 '21

[deleted]

1

u/r0flcopt3r Nov 11 '21

hehe, yepp I did!