r/linuxquestions • • 7d ago

Advice What the suitable scenarios for using Bash script?

It's been a year and a half since I started using Linux (CachyOS) as my daily driver for work and hobbies. I'm interested in learning Bash scripting to enhance my Linux experience. What are the most useful scenarios for using Bash scripts, especially for a beginner like me?

Note: I'm learning it just for fun and to enhance my Linux experience.

22 Upvotes

55 comments sorted by

6

u/jjangg96 7d ago

since you're on cachyos, one thing worth knowing early is that the default shell there is fish if you kept it, and fish isn't bash syntax. scripts are fine as long as the first line is #!/usr/bin/env bash, but pasting a bash snippet straight into the terminal can fail in confusing ways, VAR=x and for f in *; do both break.

for a first script i'd pick something that loops over files, like renaming a pile of downloads or sorting them into folders by extension. you hit variables, quoting and for loops all at once. quote every variable ("$f", not $f) and install shellcheck, it catches most beginner mistakes before you run anything.

after that the natural next step is running a script on a schedule, cron or a systemd timer, since that's where backups and cleanup jobs come from.

1

u/Independent_Cell6959 7d ago

yeah, the fish shell kinda different from bash. sometimes I encounter error wildcard things when using it. but the Fish shell is great though.

ah yes, that's interesting. sorting downloads file. noted✍️

2

u/p186 7d ago edited 7d ago

Fish is a great interactive shell and my preferred. You can still use bash scripts though. Just add the shebang as the first line of the script to tell your OS which interpreter to use to execute it.

Use this for bash scripts:
#!/usr/bin/env bash

If you have other interpreters installed like python or node, you can use those too.

#!/usr/bin/env python
#!/usr/bin/env node

Check out the Bash Cookbook

ETA: fish shell scripting can also be helpful for creating quick things but it can be limited. You can use it for advanced aliases that don’t fit as a shell alias, etc.

I use fish (primarily), bash, and nushell. Each has their benefits.

1

u/Adn0nnymous 7d ago

what do you find it’s limited on? i never write scripts in bash, i do everything in fish and i’ve found it to work really nicely for me

1

u/p186 7d ago edited 7d ago

Been a while since I wrote a FSS where I ran into an issue since I just default to bash now. I kept running into non-bash equivalents or missing language features. I’ll look through my scripts when I have a chance and see if I can remember.

ETA:
Possibly looping and issues with argument handling. The latter was simple at first but I think I had issues with inconsistencies. It was a lot easier to do in bash. It’s going to bother me now until I remember lol.

3

u/[deleted] 7d ago

Automation of a few commands.

However, when it becomes more than a few with complex flow control, I usually do it in Python, the language is cleaner.

1

u/Independent_Cell6959 7d ago

ah I see. it's like a good option for learning another language later if things got more complicated

3

u/voxadam 7d ago edited 7d ago

One of my favorite examples of bash solving real problems is abcde (A Better CD Encoder), a >6000 line bash script for ripping and encoding CDs. I used the shit out of it back in the day.

Shell scripting can be used for nearly anything, not that is should be.

2

u/Independent_Cell6959 7d ago

Dammn, >6000 line🤯 .

3

u/a1barbarian 7d ago

An excellent way to get to grips with linux. You can do three modules a day for free.

https://labex.io/

https://labex.io/linuxjourney

Have fun exploring penguin land. :-)

2

u/Independent_Cell6959 7d ago

yoo, thanks a lot. I'll looking forward to it

3

u/jessemvm 7d ago edited 7d ago

See if you can replace GUIs with CLIs.

For example, instead of using an app/applet to connect to a Bluetooth device, you can use a script that combines the following commands:

Example

EDIT: clarity and formatting

2

u/Independent_Cell6959 7d ago

Damn, this is interesting. very useful for minimal hyprland or niri setup.

29

u/Chronigan2 7d ago

Anything you do more than once that requires more than one command.

2

u/vilhelmobandito 7d ago

But why a script and not an alias?

2

u/GlassboundIllusion Nvidia KDE Bazzite 7d ago

You create the alias to invoke the script

1

u/suicidaleggroll 7d ago

Readability and maintainability

0

u/SwooshieDoll 7d ago

sounds like youve scripted a thing or two yourself, maybe you could show a girl the ropes sometime

7

u/Slackeee_ 7d ago

Just look at what you do on the commandline in your daily work or hobby. If you see repeating patterns when doing something most likely it is something you could do with a script.

1

u/changed_later__ 7d ago

Try some filesystem operations. Learn how to use `find` and pipe its output to do something else like `grep` for content inside a file `mv` it to a different directory, or `rm` it if it's trash.

1

u/Independent_Cell6959 7d ago

yeah, find, piping, and grep is very useful. I'm still learning their basic things though 😅

1

u/chuggerguy Linux Mint 22.3 Zena | MATÉ 7d ago

You can script any repetitive task.

Here's a "Just for fun":

Have fun.

1

u/Independent_Cell6959 7d ago

yoo, cool. a music randomizer

1

u/Klapperatismus 7d ago

Oh, and I recommend you to learn the awk language on top of bash. It’s stupidly small and simple and complements bash exactly for the tasks bash is bad at: looping over lines of text.

1

u/Independent_Cell6959 7d ago

Oh, yeah. I've heard of it. I'll give it a shot too after learning the basics first👍

3

u/ipsirc 7d ago

making daily backups

2

u/tuxsmouf 7d ago

That's a good example. To go further, you can create a maintenance script including backups, sending you en email with the current state of your PC or homeserver with :

date and uptime

the list of successful logins and/or failed attempts of the last day.

A check of services status like the firewall or the IDS/IPS if you got one.

A check for updates.

[...]And whatever you want or need.

1

u/dotnetdotcom 7d ago

Came to say running Rsync

2

u/Leather_Flan5071 7d ago

Anything that is repetitive or predictable or like, truncable and information retrieval.-

If you really want to learn for fun, just find case where you do some sort of work that either requires repetition, blocks of information, or automation (because bash scripts can be automated)

2

u/Klapperatismus 7d ago edited 7d ago

For small scale scripting. I use it for anything that can be done in a dozen lines or less.

For even slightly larger scripts, it’s usually better to use a different language that has better built-in string manipulation abilities. This is also better when you have to loop over output lines. You can do that in Bash but it involves a sub-shell and passing their output back is awkward. So I use Tcl for that instead.

2

u/a-i-sa-san 7d ago

I'm not going to lie, shell syntax looks like black magic once you get into the advanced stuff but it actually feels very consistent and sensible after a while.

coreutils + simple shellscripts for common tasks can do pretty much anything, because the shell is better at using all the tools everyone else has already made than anything else ever will be.

I'd rather do it in zsh than python or such, 99/100 times

2

u/skyfishgoo 7d ago

man bash

that's a kick in the balls.

https://8gwifi.org/tutorials/bash/

is good.

2

u/telcodan 7d ago

My aliases file is appalled at this question

1

u/calmeilles 30 years user, still know nothing 7d ago

My most frequently used script is one running nightly backups with rsync. Although I don't use it, cron does.

My most complex is an ingress script that pulls in image fines from SD cards or attached cameras, renames and organises them. I'm actually in the middle of refactoring that as it's grown over the years.

The there are dozens of little conveniences. Many turn complex one liners in one worders. Such as a text note to myself with the best parameters to use for a java game I occasionally play became a script to invoke the game with those params and I slapped myself for not thinking of that years before.

When you find yourself doing the same thing more than three times there's a good chance it'd be worth writing a script for.

1

u/AleWerther 7d ago

Secondo me il miglior approccio è prima avere un'esigenza, e poi cercare gli strumenti per soddisfarla. Su Linux desktop si può fare praticamente tutto dalla GUI. Ma ad esempio, se sulla tua rete domestica avessi un server headless (un cosa che puoi realizzare con un vecchio PC), allora sì che avresti l'esigenza di approfondire la riga di comando.

1

u/FryBoyter 7d ago

What are the most useful scenarios for using Bash scripts, especially for a beginner like me?

That depends on the individual user.

For example, I recently bought a trackball. However, I want to keep my mouse connected so I can use it for first-person shooters, for instance. To do this, I created a script that lets me switch back and forth between the two input devices or activate both at the same time.

There’s another script for creating backups with Borg.

There are other scripts for the version control system I use.

And so on.

In short, there really aren’t any scenarios that apply to every user.

1

u/indvs3 7d ago

I make bash scripts to make any repetitive task either less repetitive or less work-intensive.

I tend to start making more or less interactive scripts where some user input is required, then when I find myself running those scripts with the same options over and over, I edit the scripts to take input parameters, so I can set up automated systemd services that run those scripts at specific times or when specific conditions are met.

Some of those scripts include (but not limited to):

  • server/workpost hardening
  • setting up servers for specific roles
  • functional user creation
  • update automation for nodes that I'd rather not have unattended-upgrades active on

I think the ability to turn any bash script into a linux service is one of the most powerful skills you could learn, because you can build literally any sort of automated system you can imagine out of it.

1

u/RedHuey 7d ago

At its most basic, write scripts to simply daily (or recurring) tasks. Updates, backing things up, ssh-ing to a server, etc. A script does not have to be a pseudo program to be useful.

1

u/timmy_o_tool 7d ago

I have a tiny one that creates my network shares for a new install I keep on my NAS. Just a simple "mkdir" string

1

u/jeffrey_f 7d ago

Script things that:

  • Are repetitive (You do it regularly -A few times per day, week, month

    • The process doesn't take long to do, it is just boring
  • Things that become a time-sink

    • Running update, among other things
  • You forget

    • Make it cron job

SO, something a boss I had said is "if I do something once, that's fine. If I have to do it again, I make a note of it. If I must do it more, now it becomes a script/program."

1

u/toolz0 7d ago

You could just about code the entire CGI for a website server with bash, and that's a website with no static html.

1

u/The_Mild_Mild_West 7d ago

I use hyprland on CachyOS and made my own volume and brightness controls using bash.

My Keybinds file maps keys to call my bash scripts which then increment or decrement the volume/brightness. Little things like that are a fun way to learn and super low risk.

1

u/The_Mild_Mild_West 7d ago

I also have an install.sh file for my dotfiles so I can easily replicate my setup on a separate machine, which really just installs my preferred apps and packages and then simlinks my repo directories to the local config paths.

1

u/FedUp233 7d ago

Bash scripts are really handy when coupled with cron to do things periodically. You could try stuff like a cron job to cleanup older files in downloads that runs once a week or a day depending on how much stuff you download. Or goes through your home directory tree and gets rid of any older leftover editor backup files (usually prefixed with a “,” if I recall.
Or figure out how to send mail from a bash script and have it check things like free disk space daily , or smart disk status and reports problems or low resources to you in email. There are other tools to do stuff like this but rolling your own can be fun and learning.

1

u/Mediocre-Pumpkin6522 7d ago

Confession: I used tcsh but when the Linux distros started moving to bash I converted some of my tcsh to functions in .bashrc but I never bothered to learn bash scripting. My hammer is C and everything looks like a nail.

1

u/mec287 7d ago

I have a script that turns on SSH tunneling when I'm behind a access point that blocks UDP wireguard traffic.

1

u/D_FI_ANT 7d ago

A good example, I just spent 3 days (I know) creating a bash script to run HandbrakeCLI in CachyOS to select source, find all video files, set destination, recurse folder, confirm found files, create folder structure in destination with any preset I desire, error checking presets and file compatabilty, error and stall detection, full logging and cleanup, and much more. Vibe Coded all the way, sloppy but effective. I need a way to transcode ALL of my videos to different format without me being there for 3-4 days. Many compatability issues from MPEG2 old stuff recorded/digitized years ago that my older TVs cant play H265. Setup is working great, now I need a bigger CPU cooler as this cranks the cores to 100 C and the GPU runs warm. Was my first actually productive script.

1

u/BorshikNotFound 6d ago

u could potentionally use curl and unzip to make a "setup installer" for ur projects if u have something that needs some setting up

another i guess creative way to use those scripts is maybe updating packages on boot if u were to combine a .sh and ur autostart folder or i guess execute any command on boot

0

u/Guggoo 7d ago

It’s great for linking a bunch of system commands together

0

u/[unknown] 5d ago

[removed] — view removed comment

1

u/siodhe 5d ago

Reddit destroyed my long comment. I'll summarize with:

  • Never, ever put suffixes on a command
  • Best place for your own Bash programs (scripts) is in ~/bin/
  • It's common to change the implementation language of what starts as a Bash script, into , say a Python program for better handling of the data above the command the Bash script was using, and sometime even into a compiled C (or the like) program later. This is why suffixes aren't used on command - every change would either break every other script using the one being changed, or the suffix ends up being kept as a lie
  • There are huge numbers of uses for Bash programs, from wrappers around other programs, to making backups easily, to changing data formats, simplifying filenames (like from CD ripping), to cron programs, to developer support, and many, many other things
  • You can even write games in it. That guess-my-number game is good for this, where the answers are too high, too low, or correct. You can write scripts for either side, and even connect them to play each other (using a pipeline and a Unix pipe to make a ring out of the two commands)

Ref: https://www.talisman.org/~erlkonig/documents/commandname-extensions-considered-harmful/