Some good bash and bash alias tricks.

Share your own howto's etc. Not for support questions!
Message
Author
Deb-fan
Posts: 1042
Joined: 2012-08-14 12:27

Some good bash and bash alias tricks.

#1 Post by Deb-fan »

Welcome to this edition of fun with bash, bash aliases and how to run scripts via a bash alias. Also some fun with file managers is going to be thrown in too. In my case that's usually Thunar but any other file manager will do here.

Okay description of problem, I have some files I often edit and navigating to them in ie: Thunar was getting to be a real PITA, now I could've symlinked to them in any convenient location(s) and still might but what happened to pop into my head was why not use a bash alias for it, so this is the result.

Couple of prelims, you can add bash aliases to your .bashrc file kept in your users /home directory in the appropriate section of the file, however if you don't already have one let's create a dedicated file to store bash aliases (if you don't already have such a file), create a normal text file in your /home, name it .bash_aliases ... There is nothing special needed here, the syntax goes as follows, add as many aliases as you like and I encourage comments to tell yourself what the alias is/does too, here's a snippet from mine to demonstrate.

Code: Select all

# Check the systems current clock, top is cpu0, bottom cpu1
alias freq="cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq && cat /sys/devices/system/cpu/cpu1/cpufreq/scaling_cur_freq"
# Quick way to edit a file I use often.
alias tweak="/bin/bash ~/.bin/edit2.sh"
# Running a script from ~/.bin to edit a file.
alias patch='/bin/bash ~/.bin/edit.sh'
# This one is to open thunar in a directory I use often.
alias quick="/usr/bin/thunar /mnt/data/.directoryname/.blahblah/newstufftosave &exit"
That's all there is to it, the lines starting with # Are comments, bash doesn't care about them, they're there to let me know what and why I added that alias, otherwise the line beginning with alias is what's significant.

# Comment tell yourself what the alias is for or etc.
alias youralias="what-you-want-bash-to-do-when-you-type-that-alias-in-terminal"

Enclosed in "quotes" ...

Some of those are the ones I'm wanting to demonstrate here, such as alias patch="/bin/bash ~/.bin/edit.sh"

Notes: When I type the word patch into a terminal, what it does, the bash shell (which is the default user shell in a massive number of gnu/Nix distro's, including Debian(+based)then runs the designated script this ~/ is a shortcut for and just the same as typing out /home/yourusername ... In my case I have a directory named .bin in my users home, it's a .(dot) directory and that just means when you create a directory you name it with a .(dot) in front of it ie: .mydotdirectory, I like to use .directories because they aren't visible unless you unhide them, thus they don't clutter up the /home directory.

Anyway getting back to it, in that .bin directory I created a script, just a regular txt file. (end it with) the .sh extension, for shell. Here's the contents of the edit.sh file ...

Code: Select all

#!/bin/bash
/usr/bin/leafpad /mnt/data/.directoryname/.blahblah/newstufftosave/patches &exit
Begin the file with the proper shebang #!/bin/bash for a bash script, though for any script start the thing correctly. What the rest of it does, /usr/bin/leafpad is the path to the leafpad text editor binary, I could've gotten away with just leafpad or gedit or geany of whatever but whatever, what follows that is the path to the file I want to open and edit in leafpad and the &exit(probably not necessary) but that tells bash to close. So to this point, when I type "patch" in a terminal, it runs the script in ~/.bin/edit.sh, which launches leafpad and tells it which file to open and that's what it does for me. One last VERY important part of dealing with shell scripts, make them executable with "chmod +x /path/to/scriptname.sh" in my case "chmod +x ~/.bin/edit.sh" Though you can do this in a graphical file manager, can open a terminal here in tha same location as the script etc. Also note DO NOT use sudo when dealing with files or scripts-etc in your users /home, your user already owns those and mucking around in your /home files with elevated priv's like as root/sudo can cause problems, easily solved but still ... standard warning.

When I run that alias "patch" the file I want to open, opens in the selected editor and then returns the cmd prompt to my terminal/shell for me. So it's ready to take further input. The edit2.sh is also a script which does the same for another file I often end up opening/editing.


Next up this one ... Same deal, there's a directory I often end up navigating to in my file manager and click, click, clicking the way into it gets tedious quick(even named the alias quick for it.) So this opens the directory I want in my selected file manager.

Code: Select all

# This one is to open thunar in a directory I use often.
alias quick="/usr/bin/thunar /mnt/data/.directoryname/.blahblah/newstufftosave &exit"
Again surely could've just used simply "thunar" instead of path to the binary but again ... whatever. I could've created another script to do the same with thunar as was done with leafpad and the file I want to open/edit and it's easily enough done if you wanted but all this one does is launch thunar and opens it in the directory I want it to open in, that could be anywhere ie: /usr/share or / < (for opening it in the root directory.) and the &exit closes the terminal/shell. These puppies can also of course be used in keybinds(keyboard shortcuts), menu entries, icons, panel launchers or whatever else too. Any and/or every desktop or window manager should have easy means of setting up such things and the cmds you'd use are the same-similar. You should get the general idea ...

Other bash alias related stuff:

Just edit that .bash_aliases file whenever you want to add a new alias, note that they won't take effect in a given terminal, until you close + re-open the thing, so the new aliases are recognized(the .bash_aliases file gets sourced again.) Also at times it's easy to forget what aliases a person has set, to see a list of the puppies just type "alias" in a terminal and it'll list them out, though without the comments, to see those use "cat .bash_aliases" to get the full contents of the file, including comments OR setup an alias to check the contents of "cat .bash_aliases". :P
Last edited by Deb-fan on 2020-09-10 03:09, edited 1 time in total.
Most powerful FREE tech-support tool on the planet * HERE. *

sgosnell
Posts: 975
Joined: 2011-03-14 01:49

Re: Some good bash and bash alias tricks.

#2 Post by sgosnell »

If you don't want to close the terminal after editing your alias file, you can do either of these:

Code: Select all

source .bash_aliases
source .bashrc
.bashrc reads .bash_aliases automatically each time it's started or sourced.
Take my advice, I'm not using it.

User avatar
sickpig
Posts: 589
Joined: 2019-01-23 10:34

Re: Some good bash and bash alias tricks.

#3 Post by sickpig »

sgosnell wrote:you can do either of these:
Or just do

Code: Select all

. .bashrc
. .bash_aliases

Deb-fan
Posts: 1042
Joined: 2012-08-14 12:27

Re: Some good bash and bash alias tricks.

#4 Post by Deb-fan »

Appreciate the adds fellows. :)
Most powerful FREE tech-support tool on the planet * HERE. *

Deb-fan
Posts: 1042
Joined: 2012-08-14 12:27

Re: Some good bash and bash alias tricks.

#5 Post by Deb-fan »

Okay, well ... this is still fun with bash + bash aliases and also involves running a script with an alias, so putting it up here. :D

In another tute, figured out a way to auto run a script when a usb thumb drive is un/plugged by using a udev rule and started messing around with ways to get it to automatically run a bash script that will rsync the contents of a target directory to that thumb drive, while I'm still working on it and may get there someday, cooked up something that's worth sharing on the topic.

Was getting real frustrated with the situation, playing around with a bash script (and my bash skills suk!) The stupid needing priv's to even mount the usb drive, this that ... other BS !!! ARGHHHH ! So googled, came across a common sense suggestion, if you're going to use sudo cmds in a script, why not just run the script with sudo ie: "sudo /path/to/scriptname.sh". Yep ... not bad as privileged commands in it are all run with priv's, this would mean only having to enter password the one time. This however isn't what I wanted, fortunately am aware of a cool nix trick for this. A person can create a file at the following, /etc/sudoers.d and enter commands they wish to run as sudo but w/o password, clearly this is to be used with common sense and caution. Anyway ... I created a file there named myrules and added this as what's relevant to what's being discussed here.

Code: Select all

# Stuff I don't want to enter passwd to run/use.
yourusername ALL=(ALL) NOPASSWD: /usr/local/bin/backup.sh
Edit: Had to correct an oversight in the example of the /etc/sudoers.d/myrules file. Dang it, example is good to go now. Though this is one of the reasons I keep a root user acct around. Syntax mistakes in those sudoers.d files or if someone messes up the /etc/sudoers file itself with direct editing can break sudo, sudo cmds won't work and that can leave someone in a bad situation if they don't know how easy it is to fix. aka: Chroot an ailing system from live session and fix it.

In my case, with a root user, even if sudo gets borked, I just have to "su -" login as root and then can quickly fix such a syntax error to restore sudo. So if I'm in a hurry and break sudo by making a mistake in such a file, takes less than 1min to fix it. So I quit worrying about visudo long ago. While doing this edit may as well do it right, actually these files are supposed to be edited by using visudo. An example of doing that here would be "sudo visudo -f /etc/sudoers.d/myrules" it'll open that file using visudo, then if I change it and have messed up syntax, put a comma in the wrong place etc etc, when I go to save the file visudo will tell you there's a problem. Someone can just back-out of applying the changes, like closing the terminal or whatever w/o those errors being written. Google if you desire further info on using visudo and about sudoers.d.
Of course you can add more, just separate them adding a ,(comma)to the end of the last entry, then a space and add the next, no comma at the end/last one needed. What the above does is let me run the following in terminal w/o passwd needed "sudo /usr/local/bin/backup.sh" Next up we need a backup.sh file (a script) at that location, let's make it, in terminal "sudo touch /usr/local/bin/backup.sh" which creates that file, then "sudo chmod +x /usr/local/bin/backup.sh" makes it executable and from here would say open the file in a graphical text edit with sudo/root priv's so you can copy/paste what's coming up. Wait a minute before doing that.

Couple other things first, we're going to create a mount point to mount the thumb drive to when the script is run, do so with "sudo mkdir -p /mnt/usb" it creates a directory at /mnt/usb which is going to be the mount point used for this, of course peeps are free to use another location-name etc. Though /mnt is totally appropriate for this type of thing.

Plugin the thumb drive you wish to use here, we need to get the UUID of the partition on it we're going to use in the script, that's persistent across reboots, get this info by running "sudo blkid" take note of the UUID needed. In my case that's sdc1, the 1st partition on the thumb drive. ie:

Code: Select all

/dev/sdc1: UUID="7a04842f-2005-26cd-8489-09c437d410ac"
Getting there, now for opening the backup.sh script as sudo/root, in a graphical editor or command-line editor if you like ... Here's my script contents by way of example.

Code: Select all

#!/bin/bash
sudo mount -t ext2 /dev/disk/by-uuid/7a04842f-2005-26cd-8489-09c437d410ac /mnt/usb

sudo -u yourusername rsync -aAX /mnt/data/newstufftosave/ /mnt/usb/test/

sudo umount /dev/disk/by-uuid/7a04842f-2005-26cd-8489-09c437d410ac ;

exit
Gawd, now have to explain all that, 1st off something of note in the beginning of it, the "mount -t ext2" that's because my thumb drive is formatted as ext2, because it respects gnu/Linux file permissions etc etc. Now you likely have a fat32 formatted usb drive which is fine too, use "mount -t auto" instead of what I've got. /dev/disk/by-uuid/YOURUUID is where the script is targeting the usb drives partition I'm using here, plugin your drive, open a file manager and click your way into that location, you'll find your thumb drive there, though with its UUID, not mine or the one I'm using in the example above.

You can unmount and remove your thumb drive a bunch of times and check again, n again n again etc. Try some different usb ports too. Yep you'll notice your thumb drive keeps popping up there and its UUID is the same, now getting back to it ... That first line is just mounting the thumb drive based on its UUID to the chosen mount point = /mnt/usb the next line is important (for me, as again I'm using a filesystem which cares about ownership/permissions) the "sudo -u username" runs the rest of that, the rsync command as that user, so I don't have to worry about ownership-etc being changed to root when the stuff is copied by rsync to the thumb drive, in your case go ahead and use it, won't matter regardless, though not using it can depending on the filesystem you want to copy this stuff to, /mnt/data/newstufftosave/ is the source directory, it's where rsync is going to copy everything from and in my case /mnt/data is a shared ext4 data partition I've got setup to automount in /etc/fstab, again newstufftosave is just a directory on that shared data partition.

The destination directory is /mnt/usb/test/ a directory named test on the thumb drives partition, though actually rsync will create it for you w/o having to do so ahead of time. The IMPORTANT thing here is be sure you use the right paths for the source and destination. Shew, alright ... almost done, the "sudo umount" is just unmounting the thumb drive from /mnt/usb the ; is just like typing & and finally the next line ... exit, does that, exits the dang script. Clearly after you've changed things to fit your system, UUID, filesystem you're using, username etc. Save the backup.sh ... NOTE: See ps2 edit post below, if you're using fat32.


Last up here, time to add an alias, as outlined in the tute above this one, if you've got a .bash_aliases file in /home and the command-line text editor nano installed on your OS run "nano .bash_aliases" Otherwise open the .bash_aliases file with a graphical editor of choice, this is the alias I added.

Code: Select all

# Alias to rsync backup files to thumb drive.
alias usbbk='sudo /usr/local/bin/backup.sh'
And there you have it, in future, when I add or change files in that source directory, can just plugin my thumb drive, pop open a terminal and run the alias shown "usbbk" and rsync will dutifully copy stuff over to the thumb drive for me. WOOT ! Pretty cool stuff. Not quite as cool as all this happening automagically when a certain usb drive is plugged but none to shabby either. :)

Ps, Holy crap, gonna have to start putting chapters n page numbers in these monsters. There's another gd tute though. :P
Last edited by Deb-fan on 2020-09-14 01:18, edited 3 times in total.
Most powerful FREE tech-support tool on the planet * HERE. *

Deb-fan
Posts: 1042
Joined: 2012-08-14 12:27

Re: Some good bash and bash alias tricks.

#6 Post by Deb-fan »

Ps2 edit:

Code: Select all

 
#!/bin/bash
sudo mount -t vfat /dev/disk/by-uuid/YOURUUIDHERE /mnt/usb -o umask=0000,uid=1000,gid=1000

sudo -u yourusername rsync -aAX /mnt/data/newstufftosave/ /mnt/usb/test/

sudo umount /dev/disk/by-uuid/YOURUUIDHERE  ;

exit
While does work when using "mount -t auto" initially on a fat32 formatted drive, was getting permission errors w subsequent rsync writes to the thing. So the above is the proper way to mount the thing for this, umask=0000 is basically saying everything is world writable etc, uid and gid is your user/group id, default user in so many things gnu/nix is user/group 1000. Though that info is easy enough to get for a-any given user on the system in a terminal too. Anyway there you have it, best use the above for the backup.sh script for use with fat32 formatted thumb drives. Okay am happy w this now. Still digging around on finding an automagic method, arghhh. :)
Most powerful FREE tech-support tool on the planet * HERE. *

Deb-fan
Posts: 1042
Joined: 2012-08-14 12:27

Re: Some good bash and bash alias tricks.

#7 Post by Deb-fan »

Code: Select all

#!/bin/bash

# This is the entry for an ext2 formatted thumb drive.
if [ -e /dev/disk/by-uuid/YOUR-UUID-GOES-HERE ]; then
	sudo mount -t ext2 /dev/disk/by-uuid/YOUR-UUID-GOES-HERE /mnt/usb

sudo -u yourusername rsync -aAX /mnt/data/newstufftosave/ /mnt/usb/test/

sudo umount /dev/disk/by-uuid/YOUR-UUID-GOES-HERE ;

fi

# This is for a fat32 formatted thumb drive.
if [ -e /dev/disk/by-uuid/YOUR-UUID-GOES-HERE ]; then
	
	sudo mount -t vfat /dev/disk/by-uuid/YOUR-UUID-GOES-HERE /mnt/usb -o umask=0000,uid=1000,gid=1000

sudo -u yourusername rsync -aAX /mnt/data/newstufftosave/ /mnt/usb/test/

sudo umount /dev/disk/by-uuid/YOUR-UUID-GOES-HERE ;

fi

exit
Okay, went back to the drawing board, thought of "hey, must be fairly easy to run(source) a script from within a script", popped into my bean, yeah my current script obsession is getting out of hand apparently. :D

The above could be used for doing that too, though what I'm wanting to demonstrate with this is running the rsync operation for more than one thumb drive, based on whether they're plugged in or not. Obviously as shown these drives are formatted with different filesystems, one is ext2 ... the other fat32 clearly. Using the if statements in the script let's me target more than 1 thumb drive with the script, when the ext2 drive is plugged, a symlink for it's UUID is created in /dev/disk/by-uuid/ITS-UUID-HERE and that's what the bash script checks if either of the thumb drives UUID's or BOTH are there ... meaning the drives are plugged, when I use the alias I set in .bash_aliases as described above it runs the the script at /usr/local/bin/backup.sh and WHAM rsync does its magic. Also will do the backup to both of them, if both happen to be plugged in.

If neither drive were plugged in and used the bash alias, the bash script just exits. Even cooler and much cleaner than having to bother with making more than one script or adding a bunch of aliases for usb.drive-A, B and C etc. :)
Last edited by Deb-fan on 2020-09-14 01:28, edited 1 time in total.
Most powerful FREE tech-support tool on the planet * HERE. *

Deb-fan
Posts: 1042
Joined: 2012-08-14 12:27

Re: Some good bash and bash alias tricks.

#8 Post by Deb-fan »

Had to do a correction on info related to sudoers.d above. Arghhhh fixed it though. :)

It's a dang good trick to know period. A lot of interesting uses for it. Now that I've cleared that file in my case that's /usr/local/bin/backup.sh so I can run privileged cmds in that script w/o entering a password, can use it for a bunch of useful things by doing similar to what's shown, using conditionals and if statements etc to only run(source) xyz-script or series of commands when the situation I'm going for matches it. All of which won't require entering a password. Also as shown a person can elect to run a particular part of a bash script as their normal user whenever appropriate too.

The adventure on this continues of course and as usual with almost anything gnu/Linux of course turns out there's an endless number of interesting/cool things related to doing something like automatically executing a script on plugging in a certain usb device. Fiddling around with a util included with udisks2 named udisksctl which can mount usb's and other stuff as user without need of passwd but so far it's finicky, really due to user ignorance at this pt, got it working but like the approach outlined above better. It's=udisksctl still cool and worth learning about. Turns out people can use stuff in a udev rule file now which will run a systemd service unit, thus it can execute a given script on a certain device un/plug too.

Haven't fully figured it out yet but apparently the RUN+= part of udev rules is often dirty/hacky, known to be misused and abused compared to using these newer systemd elements someone can use in a udev rule. Couple of those udev thingy's being ie: ...

TAG+="systemd"
ENV{SYSTEMD_WANTS}=="nameoffile.service"

Googling such is sure to bring up related info to this. At the moment I'm goodly and truly burnt out on screwing with this !!! Errrr ... actually was already that and more 12hrs ago !!! Still hopefully this inspires nixers and helps give them a leg up in learning this junk.
Most powerful FREE tech-support tool on the planet * HERE. *

Deb-fan
Posts: 1042
Joined: 2012-08-14 12:27

Re: Some good bash and bash alias tricks.

#9 Post by Deb-fan »

Just more hair brained nixness wanted to share, also at this point these tutes are starting to bleed together and over-lap, junk from one could be very relevant to or supplement other how-to's but in one of these suckers noted an interest in running a bash script when a certain usb thumb-drive or device is plugged, this tute shows how to target however many usb-drives a nixer wants for doing a backup, using it's UUID in an if statement ... as demonstrated above but doesn't cover automagically doing so. Well using a crontab which executes this script however often someone wanted and set it to ie: Every 30secs or whatever, it's not going to add much, almost nothing by way of system overhead and in such a scenario, when one of the usb's I've setup to be included in the script is plugged, for as long as it's plugged, any new files or files I update-change in that source directory would be rsync'ed to the backup directory every 30secs. Rsync only writes the changes anyway, one of it's many AWESOME qualities obviously ...

Not doing a write up about the particulars of doing such, no doubt PLENTY of good one's easily found on the interwebz already. Setting up a crontab to run a script etc. Some obvious refinements present themselves, such as if that drive is already plugged, that could be used as the match vs mounting it at ie: /mnt/usb etc, if not, then the script could be told to yep, mount it there and perform the backup. Such a thing could complement some of the junk outlined in this thread though. Just wanted to share the general idea, as again ... It might motivate people to figure out how to do something cool and useful with their Debian gnu/Nixy goodness. :D

Ps, yet more nonsense, there's a golden principle for techies or should be and it goes as follows, "Thou shall not waste much time + effort reinventing the wheel, unless you're stupid or enjoy doing such." RAmennnnnnn, in other words there's TONS of scripts and scripting examples people have posted online, so search for those, learn from or use them for xyz-thing you're trying to do. DAMMIT, this brings another principle to mind, "Thou shall not run unknown mystical looking commands or scripts you don't understand on thy nixy goodness, otherwise you ARE stupid and deserve any self-inflicted pain and suffering which results." RAmennnnnnn. Plenty of great resources online, plenty of bad and/or horrible, some malicious ones too, so always keep that in mind okay ? These things are key to happy nixing.

Alright ... another post done, YAY! :P

Ps, arghhhh, more .. actually this arrangement could work very well for autodevice detect and reconfig, a nixer here was having an issue with a microphone or whatever, found + shared a fix and scripted it. Just needed an automagic way to run such on device plug, a crontab and conditionals, if statements in a bash script set to run every 2-3 secs could do this nicely. When something is plugged udev + dbus, systemd, one of the nix OS subsystems is going to predictably make some change that could be targeted in a bash script. Also such a script properly structured could be set to check a certain value and simply exit, such as would be the case if the device is configged as the user wants.

While there are other approaches certainly, think this could be a fairly good one too. NOW another post done, yep ... YAY!!! Gdammit! :)
Most powerful FREE tech-support tool on the planet * HERE. *

Deb-fan
Posts: 1042
Joined: 2012-08-14 12:27

Re: Some good bash and bash alias tricks.

#10 Post by Deb-fan »

Ps, chapter 23, pg. 375, subsection k.) Lmfao, arghhh. :P

Still want to clarify so adding https://askubuntu.com/questions/800/how ... -5-seconds , this baby and https://twpower.github.io/212-systemd-timer-example-en yep a systemd timer is better, never heard of mcron considering the sheer momentum behind systemd's development and integration using one of its features should always be a first thought, it was for me anyway, that being use of a timer unit.

Also of course still other means to this end, event triggered responses, like running scripts or reconfig cmds on a targeted device when plugged. Hacking cron would be dirty and nasty with much better and cleaner options avail. Fact time has come to determine why-the-hades i should even keep cron around ? Extraneous services are a bigtime no, no. :) Hadnt occurred it can't handle computing tasks in secs w/o ugly hackery ... WTH, WHY? That's ridiculous in the context of something like computing.
Most powerful FREE tech-support tool on the planet * HERE. *

Deb-fan
Posts: 1042
Joined: 2012-08-14 12:27

Re: Some good bash and bash alias tricks.

#11 Post by Deb-fan »

Okay and now cometh more bash dorking. :D

A recent thread about setting a default power governor got me messing around with this approach. Figured it out to my satisfaction and sharing the results. In the following, I'm switching the governor in use w/o password, just another crappy bash script created in /usr/local/bin named mine pgov.sh You need to chmod the thing to make executable as shown through-out this thread and need to add it to whatever file or make a new one if you don't have one as described above also in /etc/sudoers.d so that any privileged commands can be run by your user w/o entering passwd. Anyway at this point I've got an executable file /usr/local/bin/pgov.sh here's the contents.

Code: Select all

#!/bin/bash

	query=$(cat /sys/devices/system/cpu/cpufreq/policy0/scaling_governor)

if [ "$query" == "ondemand" ]; then

	echo performance > /sys/devices/system/cpu/cpufreq/policy0/scaling_governor && echo performance > /sys/devices/system/cpu/cpufreq/policy1/scaling_governor

else

	echo ondemand > /sys/devices/system/cpu/cpufreq/policy0/scaling_governor &&  echo ondemand > /sys/devices/system/cpu/cpufreq/policy1/scaling_governor

echo 30 > /sys/devices/system/cpu/cpufreq/ondemand/up_threshold 

echo 4 > /sys/devices/system/cpu/cpufreq/ondemand/sampling_down_factor 

echo  250000 > /sys/devices/system/cpu/cpufreq/ondemand/sampling_rate

fi

exit 0
In my case I'm checking a file with a query, if that files content is "ondemand" it runs the next stuff, setting the performance power governor on both of my dual-core's processor cores. Clearly if you have more cores, prefer other governors etc, adapt this junk to reflect that. Which that governor (performance)will run w cores at max-freq until I re-run or trigger this script. That can be done via bash alias, keybind, panel launcher, desktop icon, menu entry etc. Simply by using "sudo /usr/local/bin/pgov.sh" in them to run the script. When I want to switch back to the ondemand governor, that's what I'd do, run it again via whichever means, the script notes that files value is NOT set to "ondemand" thus runs the cmds after the else in the script, that sets ondemand back as the governor being used.

NOTE: That string of cmds after the ondemand governor has been set are tweaks/preferences which I'm applying to adjust the ondemand's up_threshold, sampling_down_factor and sampling_rate, you may want other things in which case, yep ... obvioulsy remove those lines from this script. The interesting thing I noted and why I had to add those lines, I was adjusting those settings via a script that gets run at system startup. However when doing the above, switching to performance and back to ondemand, noticed all the defaults normally used with the ondemand governor get restored and those defaults suck, so did that to reset them to my preferences.

Whatever you set these to needs to be one of the scaling governors available on your system of course, easy to find out which those are, ask google how ... End result, this gives a great example of how you'd set such a thing up on your system and what doing so let's me do, switch between power governor's on-the-fly w/o bothering with stuff like cpupower or entering a password, blahblah. That's a wrap on this nonsense. :D

UPDATE:

Wanted to post a cleaner way to deal with the pgov.sh script, it's just messy having to add so many repeated lines and if someone were doing this on a quad or more cores it'd be a pain. Plus it's just a cool bash trick, good ole "for i in". In the below my old beloved beastie laptop is a dual-core, so I'm using [0-1] in the script, if you had a quad-core, yours would be [0-3] 0, 1, 2, 3 = 4 cores. So yeppers someone with a quad would use that instead. Anyway w/o further ado, the cleaner version of this script ...

Code: Select all

#!/bin/bash

	query=$(cat /sys/devices/system/cpu/cpufreq/policy0/scaling_governor)

if [ "$query" == "ondemand" ]; then

	for i in /sys/devices/system/cpu/cpufreq/policy[0-1] 
do
	echo performance > $i/scaling_governor
done

else

for i in /sys/devices/system/cpu/cpufreq/policy[0-1]

do
	echo ondemand > $i/scaling_governor 

echo 30 > /sys/devices/system/cpu/cpufreq/ondemand/up_threshold 

echo 4 > /sys/devices/system/cpu/cpufreq/ondemand/sampling_down_factor 

echo  250000 > /sys/devices/system/cpu/cpufreq/ondemand/sampling_rate

done

fi

exit 0
Someone could use this to simplify, cleanup and do cool things in their bash scripting adventures.
Last edited by Deb-fan on 2021-01-04 05:17, edited 1 time in total.
Most powerful FREE tech-support tool on the planet * HERE. *

CwF
Posts: 1115
Joined: 2018-06-20 15:16
Has thanked: 1 time
Been thanked: 4 times

Re: Some good bash and bash alias tricks.

#12 Post by CwF »

Deb-fan wrote:easy to find out which those are, ask google how
No, don't ask google. I ask the cat!
For sniffing around in sysfs I made a simple custom action for Thunar.

Code: Select all

<action>
	<icon></icon>
	<name>probe</name>
	<unique-id>01011970</unique-id>
	<command>cat %f | zenity --title="says the cat" --text-info  --width=480 --height=120 --cancel-label=ok --ok-label=cool</command>
	<description>ask the cat</description>
	<patterns>*</patterns>
	<other-files/>
	<text-files/>
</action>
As I mentioned in that governor thread lots of magic is in /sys. Different packages and different hardware enumerate in this tree refered to as 'sysfs'. Things don't have to, but when they do, you can learn about them there by probing, asking the cat, and find some have appropiate settings to transfer to etc/sysfs config files. Not used much.

On subject is the tree created when cpufrequtils is installed, probe it!
Also /sys/class/hwmon/ is a nice place to find sensor information. Some things are editible here, or can be referenced for genmon's or others.
Elsewhere in there you can find commands for rare hardware actions for disc controllers, or driver binding and unbinding, etc. You can rotate hardware between a host and a vm for example.

You can also hang a file manager, freeze the system, and likely hose hardware, so have fun!

cpupower does the same, and does have cpupower-gui to give you a nice tool instead. I like the extra commands I think come from this. I sometimes use a genmon or terminal to watch socket power.

Code: Select all

turbostat --quiet --show PkgWatt

Deb-fan
Posts: 1042
Joined: 2012-08-14 12:27

Re: Some good bash and bash alias tricks.

#13 Post by Deb-fan »

^ Was starting to get lonely in here. :D

Not that there's anything wrong w utils, big part of the coolness of this is how simple and effective it is w/o need of utils, extra services or daemons and certainly no chance of hosing hardware. My bash skills still stink but easily hobbled together lots of useful junk. That above, a way to automagically rsync to however many backup usb drives, what, when, where, whenever wanted, if they happen to be plugged in.

Put together one to run fsck too, not shown but idea is in the backup script. If plugged, checks if xyz-usb is mounted, if is, unmounts runs the appropriate fsck tools-cmds on them for the filesystem being used, wham done. Just an easy way to make sure those are all not corrupted and have clean filesystems. Though left that one to require passwd and want to oversee that when its done for obvious reasons.

Trying to share some useful info too o course. Give people interesting ideas and junk they can do-use on their systems. :) That other thread you're talking about, lol ... yeppers lordy, :) things in this tute could actually easily be adapted to set default governor on user login too. Am done with that monster thread though, shrugs. :P
Most powerful FREE tech-support tool on the planet * HERE. *

User avatar
Head_on_a_Stick
Posts: 13450
Joined: 2014-06-01 17:46
Location: /dev/chair

Re: Some good bash and bash alias tricks.

#14 Post by Head_on_a_Stick »

Deb-fan wrote:

Code: Select all

	query=$(cat /sys/devices/system/cpu/cpufreq/policy0/scaling_governor)

if [ "$query" == "ondemand" ]; then
If you're using bash then you should prefer the [[ test instead of the POSIX [ test. Your script doesn't need bash though so you could change it to #!/bin/sh and keep the [ test, if you do that then use = instead of == (both will be accepted by most shells but only the former is specified in the POSIX standard).

And there's no need for cat:

Code: Select all

read -r query < /sys/devices/system/cpu/cpufreq/policy0/scaling_governor
HTH
Black Lives Matter

Debian buster-backports ISO image: for new hardware support

Deb-fan
Posts: 1042
Joined: 2012-08-14 12:27

Re: Some good bash and bash alias tricks.

#15 Post by Deb-fan »

^ Cool, thank you ever so much old chap. :)

Ps, also thanks for the add n share @CwF, looks like a cool thunar trick. Was too busy jumping to defend the command-line to read anything. :)
Most powerful FREE tech-support tool on the planet * HERE. *

Deb-fan
Posts: 1042
Joined: 2012-08-14 12:27

Re: Some good bash and bash alias tricks.

#16 Post by Deb-fan »

Okay, well of course wanted to add something, errrr actually screwing around with links2 a cli web browser and had to test out posting. Thing is actually kinda cool, well depending on if this post works.

If it does, some random stuff about those thunar aliases, use those in a keybind, rather than having it open in /home, spend much more time in a data partition and it's nice having thunar open at that location in the filesystem instead. Another quick navigation trick thunar in all its file manager awesomeness, just hit Control + L and type out where you wish to go, even helpfully will offer auto-complete to get a user there faster. Of course am sure its a common feature in tons of graphical file managers, still thunar is good stuff. :P

If this works, suggest folks give links2 a spin, its interesting, does allow mouse click too even though of course is bound to take some getting used to. Someone is fed up with the horrid bloat of modern web browsers, why not play with a cli browser ? :)

Trying out edit: Hoas will be so proud, lmao. Yep, fricken thing is cool. Tip: The pg up-down seems to really help in sorta scrolling pgs, though likely a better way too. Also hitting hte Esc key pops up a handy menu thing. Haven't dorked with this in a long time, the tiny amount of system overhead it has is wild. Okay, end test. :)
Most powerful FREE tech-support tool on the planet * HERE. *

User avatar
bester69
Posts: 1900
Joined: 2015-04-02 13:15
Been thanked: 1 time

Re: Some good bash and bash alias tricks.

#17 Post by bester69 »

To shorthen long paths
:P

Code: Select all

alias bashorten='PROMPT_DIRTRIM=1'
Last edited by bester69 on 2020-12-06 04:25, edited 1 time in total.
bester69 wrote:You wont change my mind when I know Im right, Im not an ...

User avatar
RU55EL
Posts: 539
Joined: 2014-04-07 03:42
Location: /home/russel

Re: Some good bash and bash alias tricks.

#18 Post by RU55EL »

bester69 wrote:To shorthen long paths
:P

Code: Select all

alias bashorten='PROMPT_DIRTRIM=1
I think you mean:

Code: Select all

alias bashorten='PROMPT_DIRTRIM=1'

Deb-fan
Posts: 1042
Joined: 2012-08-14 12:27

Re: Some good bash and bash alias tricks.

#19 Post by Deb-fan »

Here's a fun one for the new year ... Been wanting to put together a script to handle chrooting an OS-install for awhile, so decided to dork with it and got a working one setup to my satisfaction, so sharing the outline here ...

Okay someone would need to create a file in their users /home directory, name it test.sh, make it executable with the standard "chmod +x test.sh" or however you want to do that ie: If you wanted to do so in a file manager to give it executable permissions. Then here's the contents ...

Code: Select all

#!/bin/bash

echo # these are ugly as feck but put them in to give newlines to improve readability.
echo "Enter the drive and partition to target ... ie: sda1, sdc2 etc."
read DRIVE # This saves the value the user enters to a variable called DRIVE.
echo
echo 
echo "Enter the type of filesystem on the partition ... ie: ext2, ext3 or 4." 
read FST # short for filesystem type here. :)
echo
echo "Confirm this is the correct drive, partition and filesystem type before proceeding ... Target is $DRIVE ... which is formatted as $FST ?" 
read -p "Proceed with live chroot of $DRIVE, press y to continue. " -n 1 -r 
sleep 1s && echo

if 

[[ $REPLY =~ ^[Yy]$ ]] 
then
sleep 1s &&
echo "YOU ASKED FOR IT BUDDY, now you're gonna GET IT!!!! :o<"
sleep 1s &&
echo 
echo "HAPPY NEW YEAR!!! :o)"

fi

exit 0
Save it, open a terminal and type in ". test.sh" to run it. What it does, asks the user to input the drive and partition, then saves the value they enter in a variable called DRIVE, then asks for the filesystem type and does the same, saves the value that's entered into a variable called FST, then offers a prompt ... if someone hits any key other than Y/y it just exits the script but if y or Y is entered it runs the rest of it. In the above there ends up echo'ing You asked for it, etc ... HAPPY NEW YEAR to the screen. :D

Okay time for the working script, handles ext2-3 and 4. Really don't need to even bother with asking for the specific filesystem type, mount would be smart enough to handle it without it but wanted to add it anyway, so did ... Also in the case of someone who has a separate /boot partition(which I don't) that would have to be mounted too, in order to do something like reinstalling grub, same for situations with a GPT system, which has a ESP (efi partition on it, again I don't so didn't bother, this is an old bios-mbr laptop.) Anyway, confirmed it working on several partitions on my old beastie.

Code: Select all

#!/bin/bash

echo # these are ugly as feck but put them in to give newlines to improve readability.
echo "Enter the drive and partition to target ... ie: sda1, sdc2 etc."
read DRIVE 
echo
echo 
echo "Enter the type of filesystem on the partition ... ie: ext2, ext3 or 4." 
read FST # short for filesystem type here. :)
echo "Confirm this is the correct drive, partition and filesystem type before proceeding ... Target is $DRIVE ... which is formatted as $FST ?" 
read -p "Proceed with live chroot of $DRIVE, press y to continue. " -n 1 -r 
sleep 1s && echo

if 

[[ $REPLY =~ ^[Yy]$ ]] 
then
echo
echo "Don't forget to exit with Ctrl + D and run cleanup.sh to unmount everything cleanly after leaving the chroot."
sleep 2s &&
sudo mkdir -p /mnt/chroot
sudo mount -t $FST /dev/$DRIVE /mnt/chroot
sudo mount -t proc none /mnt/chroot/proc
sudo mount -o bind /dev /mnt/chroot/dev
sudo mount -o bind /dev /mnt/chroot/dev/pts
sudo mount -o bind /sys /mnt/chroot/sys
sudo cp /etc/resolv.conf /mnt/chroot/etc/ # Live session needs to be online for this to matter but won't hurt anyway.
sudo chroot /mnt/chroot

fi

exit 0
Couple things to point out there, I'm using this from a live session, modified a live ISO, so I could add custom keybinds, bash aliases and scripts to it like the above. Am triggering the thing with one of those bash aliases I set in .bash_aliases. Point I'm wanting to make there is if someone were using this in another context = like on an actual bare metal install, they wouldn't need to recreate the mount point directory everytime it were used, so obviously get rid of the line if using it for that purpose, this one ....

"mkdir -p /mnt/chroot", no need to create an existing mount pt over and over. Am going to use this on bare-metal installs too. If someone is multibooting on a system can be useful to be able to just quickly chroot other installs on that system should need arise. Also as the script mentions, would go ahead and get in the habit of exiting a chroot properly, Ctrl + D and here's the commands to unmount everything cleanly, again I just went ahead and scripted it, so that when the script's run just goes through that series of commands, here's the cleanup.sh contents too.

Code: Select all

#!/bin/bash

sudo umount -l /mnt/chroot/dev/pts
sudo umount -l /mnt/chroot/dev
sudo umount -l /mnt/chroot/proc
sudo umount -l /mnt/chroot/sys

exit 0
Really see no harm in getting into the practice of going through the above and cleanly unmounting everything, on a live session chroot really no biggie but again on bare-metal feel better running through it. Purpose of this is if you do need to chroot an install, it's tedious running through all the cmds to do so, same for all the cmds to unmount and this puppy makes it a snap.

Another naggler to be aware of, as noted in the script too, the live session OS actually needs to be online, connected to the internet for that line to work/matter, if not you'll just end up with an empty file in /etc/resolv.conf which I just found out, as noted, tested the chroot.script on my bare-metal installs. One of which was on sda1, went to go online and kept getting "can't find sever, blahblahblah" in my browser. Took a min to think to check the resolv.conf file and had to replace it with a working one to get that OS back online. Just want to note it as something to be aware of.

Other than that, it's good to go, if I want to chroot one of the Nix Os's on a pc. Fire up live session from the usb and trigger the chroot.script to run, it asks me which drive and partition, what filesystem type, then asks me to confirm by pressing y = yes and if I do so, then runs all the cmds to chroot that OS and reminds me to cleanly exit the chroot and cleanup, unmount everything afterwards.

Anyway, this shares enough of the idea if anyone cares to play with or expand upon it and that's a wrap. Happy new year fellow nixers. :D
Most powerful FREE tech-support tool on the planet * HERE. *

User avatar
Head_on_a_Stick
Posts: 13450
Joined: 2014-06-01 17:46
Location: /dev/chair

Re: Some good bash and bash alias tricks.

#20 Post by Head_on_a_Stick »

Simpler alternative that provides a menu listing the available partitions (call the script with sudo or run it as root):

Code: Select all

#!/bin/bash

_list_part()
{
   # list all partitions except swap & those already mounted
   lsblk -lno name,type,mountpoint | awk '/part/&&!/\//&&!/SWAP/{print $1}'
}

_select_part ()
{
   readarray -t lines < <(_list_part)
   
   local PS3="Choice: "
   echo "Please select the target root partition:"
   select choice in "${lines[@]}"; do
      if [[ -n "$choice" ]]; then
         break
      else
         echo "Invalid choice, please try again." >&2
         continue
      fi
   done
}

_chroot ()
{
	mount /dev/"$choice" /mnt
	arch-chroot /mnt mount -a
	arch-chroot /mnt
	umount -R /mnt
}

_confirm ()
{
	while true; do
		echo "Target partition is /dev/${choice}, it will be mounted on confirmation."
		read -re -p "Is this correct? [Y/n] "
		case "${REPLY^^}" in
			N|NO)
				break
				;;
			''|Y|YES)
				_chroot
				exit 0
				;;
			*)
				echo "Unknown response, please either confirm or deny." >&2
				;;
		esac
	done
}

main ()
{
	while true; do
		_select_part
		_confirm
	done
}

main
That uses arch-chroot(1) (from the arch-install-scripts package) to bind mount the API filesystems, copy over /etc/resolv.conf and tear down the bind mounts after exiting.
Deb-fan wrote:in the case of someone who has a separate /boot partition(which I don't) that would have to be mounted too
The "mount -a" line mounts all partitions listed in /etc/fstab in the target root partition.
Deb-fan wrote:"mkdir -p /mnt/chroot", no need to create an existing mount pt over and over.
/mnt is intended for temporary mount points so why not just use that directly?

EDIT: refactored script to use functions.
Black Lives Matter

Debian buster-backports ISO image: for new hardware support

Post Reply