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

Re: Some good bash and bash alias tricks.

#21 Post by Deb-fan »

Hey, cool ... all good suggestions so thanks Head_on. Was hoping some folks would improve on the idea. Been advocating that this type of thing would make a good addition to hybrid/live media and finally got around to playing with it myself. Could just be a nice touch to add to live media as part of rescue tool-kit or tool on the ISO. Definitely has tons of room for improvement or expansion ...

Are already polished tools to make reinstalling a borked bootloader easy and/or automagic, adding things to detect or automount an ESP or separate /boot wouldn't be overly difficult ( that trick you/@Head_on posted looks good) and same should be said for dealing with encryption in this mess if the user happens to be one of those nixers who encrypts everything.

For myself, when I modded the ISO, created permanent/predictable mount points on it, so don't need to create /mnt/chroot or use those lines in the chroot.script. Still BIG +1 on why not just use /mnt ... hadn't thought of that ... Though was playing with a couple other refinements of this thing and went ahead and tried them out so want to share findings on it.

The thing about copying resolv.conf from the live session to one of my bare-metal installs crapping things up, decided to go with this to handle it.

Code: Select all

sudo cp /mnt/chroot/etc/resolv.conf /mnt/chroot/etc/resolv.conf.bak # Make a backup of targets resolv.conf if present.
sudo cp /etc/resolv.conf /mnt/chroot/etc/ # Live session needs to be online for this to matter but won't hurt anyway.
Just added that line to the script to make a backup of any resolv.conf file that's on the target partition and rename it resolv.conf.bak. So it'd be easier to restore the thing afterwards ... Also ended up tweaking the cleanup.sh script a bit too, its contents are now as follows ...

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
echo "Enter the drive and partition to unmount now ... Check your typing."
read UNMT && echo "preparing to unmount $UNMT"
read -p "Press y to continue. " -n 1 -r
if [[ $REPLY =~ ^[Yy]$ ]]; then

sudo umount /dev/$UNMT

fi

exit 0
Added another dialogue to it, so that the script asks which drive/partition should be unmounted. I was talking about unmount everything cleanly, blahblahblah and forgot to include unmounting the actual target itself. :P So in the above there, it asks which drive-partition that is, saves what's entered to the variable UNMT and again used the Y/y prompt so a user can confirm it, otherwise again ... the script just exits.

Can see a lot of potentially useful junk that could be integrated into this type of thing but don't have all the needed hardware on hand to test everything, honestly am not the best qualified to sort all of it out either. Plus all this works perfectly as is for me personally, don't want to try too hard in even attempting to make everything imaginable work for every configuration people may have or want. It's a good idea overall, got things working for me, proof of concept. Though again Head_on thanks for the tips and input on this, good stuff. :)
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.

#22 Post by Head_on_a_Stick »

Deb-fan wrote:the script asks which drive/partition should be unmounted
The man page does not recommend that approach:
umount(8) wrote:Giving the special device on which the file system lives may also
work, but is obsolete, mainly because it will fail in case this device was
mounted on more than one directory.
Use the actual mountpoint in the filesystem instead.
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.

#23 Post by Deb-fan »

^ Say again ... in mere mortal speak this time please Hoasinator ? ... Kidding :), don't see the harm in it, at least not in this context but I could be missing something too. You're talking to a guy who didn't think of using /mnt for all of this, that really is fraggin brilliant. You've probably mentioned it elsewhere but didn't recall it. All this dang time I'd been typing out huge full paths for junk like this and /mnt was sitting there laughing at me the whole while !!!!

DAM U MNT !!!

Do appreciate the tips and feedback. Hoping whomever will adopt it and polish the concept up, add ncurses menu's and automagicness to the thing or whatever else. May very well be existing tools of this type, haven't really checked around so wouldn't be surprised, regardless think it's useful and hobbled together a working solution for personal use. Now shared some of what I discovered while dorking with it so my work here is done and it's time to do some more critical work ... like watch a movie. :D
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.

#24 Post by Deb-fan »

Was thinking further about this nonsense and came up with the following brainfart on it to share.

REALLY COOL: One downside to this chroot.sh and cleanup.sh affair is having to bother with separate scripts for them which require user interaction. Meaning user has to enter the target drive + partition in both, getting confirmation etc. Which hey is still cool but not uber-l33t as is befitting of meself, LOL ... anyway here's an idea to make the magic happen without that, what if as part of the chroot.sh it creates a file and stores(echo's)the value of the $DRIVE variable to it ie: sda1 or sba3 or whatever else,then the cleanup.sh could be setup to read that and apply it, still echo confirmation to user of which it is just for the sake of it and do the Y/y thing. (or not ... could make it automagic too I guess.)

Lines in chroot.sh would look along the lines of.

sudo touch /path/to/storage.file # To create the thing and then.
echo $DRIVE > /path/to/storage.file # To echo the value of $DRIVE to it.

And cleanup.sh as follows in the appropriate place.(top of script)the rest would just be as shown if were wanting to keep the confirmation deal vs just proceeding seamlessly, atm dunno which to prefer ...

Code: Select all

#!/bin/bash

DRIVE=$(cat /path/to/storage.file)

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
echo "Preparing to unmount $DRIVE"
read -p "Press y to continue. " -n 1 -r
if [[ $REPLY =~ ^[Yy]$ ]]; then

sudo umount /dev/$DRIVE

fi

exit 0
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.

#25 Post by Head_on_a_Stick »

Deb-fan wrote:Hoping whomever will adopt it and polish the concept up, add ncurses menu's
Here's a version that uses whiptail for a similar effect:

Code: Select all

#!/bin/sh

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

_select_part ()
{
   # shellcheck disable=SC2046 # word spitting is needed for the _list_part function
   choice=$(whiptail --notags --menu "Please select target root partition:" 0 0 0 $(_list_part) 3>&2 2>&1 1>&3)
   if [ -z "$choice" ]; then
      exit 1
   fi
}

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

_confirm ()
{
   if whiptail --yesno "Target partition is /dev/${choice}, is this correct?" 0 0 0; then
      _chroot
      exit 0
   fi
}

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

main
It's slightly off-topic for this thread because I've swapped from bash to POSIX sh, hope you don't mind.

Scrot or it never ran:

Image

:)
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.

#26 Post by Deb-fan »

^ No definitely welcome and that looks pretty cool. :D Any all such ideas you or anyone else want to introduce on this topic are encouraged.

Ye gawds bunch of other junk is possible too. Looping the dang chroot.sh or putting it to sleep and then nagging the person to confirm and run the part in the cleanup.sh or if they were to hit anything other than Y/y loop again and bug them again a few mins later, lmao ...

Also really wanting to tackle the damn separate boot and/or if it's dealing with an encrypted partition thing but DO NOT want to dump the time into it, as I don't ever setup a separate boot nor use whole disk encryption either. So it'd just be investing time for the sake of it at this point. Could wipe-out one of my thumb-drives and set up a boot + encrypted install on it but it'd be a real PITA to restore the junk I've got on the only usb drive I have that could be used for this crap. :(

Kinda hoping someone who already has the appropriate setup or a system more prone to experimenting might pitch in on it a bit. This old thing doesn't even support virtualization and I'm not installing Virtualbox and going through all of that for the sake of something I don't have much use for anyway.

Either way I hitherfor... or it might be hitherto .. approve of the inter-scripting communication idea as outlined in that post above, could use that type of thing for a bunch of interesting stuff. :D
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.

#27 Post by Deb-fan »

Cooked up another fun one, of course kept dorking with the chroot.sh idea and it's coming along(errrr mostly/sorta :) )and this is a technique planning to integrate into the project. Using while to loop a script.

Create a file in your users home directory, I named mine trigger.file ... Next up create the script for this, named the one I used loop.sh and make it executable "chmod +x loop.sh" or however you want to set it to be executable ...

Code: Select all

#!/bin/bash

while [ -e /home/yourusername/trigger.file ]; do

sleep 2 

done

touch /home/yourusername/yepworked.file
Explanation of that, when while is used as long as the condition is true, the script keeps running whatever commands are set. In the above there that condition is for as long as the file named trigger.file exists ( the -e /path/to/filename part in it)at the specified location /home/username/trigger.file then it's true and the script runs the commands, in the above, the command is sleep 2 (go to sleep for 2secs)then it runs again, will keep doing so until the condition is false or the terminal is closed etc. You could use whatever series of commands or whatever else you like there of course. Anyway when I delete trigger.file, then the condition is no longer true, trigger.file no longer exists so the condition is false and the script runs the next commands, which is to create a file named yepworked.file in your users home directory in this script.

To run the script.

Could type out the full path to it in terminal ie: /home/yourusername/loop.sh or just ". ~/loop.sh" the "~" tilde in that is the same as typing out /home/yourusername or pop open a terminal ( which your users home should already be the working directory when you open new terminals) and type "source loop.sh" or again just ". loop.sh" the .(dot) is just like typing source. Simple, cool and weird ... also fun. Am going to use this to execute another script within 2secs of a certain file being removed. For that I only have to use the path to the script in place of touch /etc/etc/yepworked.file.


Still dorking with it but a cool addition to this, kind of amusing to background the process. Just add an "&" to it ... ". loop.sh &" so the terminal's command prompt is returned and it'll keep running in background. Have more dorking yet to do and quality time to spend with Google until coming up with something that fits what I'm after. Though hopefully this is an amusing bit of shellery that might come in handy for you. :D
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.

#28 Post by Deb-fan »

Not so fast ! Here's another amusing idea that could actually have interesting applications. The self destructing script.

Create an example script, named it imoutofhere.sh make it executable as normal and here's the contents.

Code: Select all

#!/bin/bash

touch /home/yourusername/YAkilledME!
echo "gee thanks dude/tte!" > /home/yourusername/YAkilledME!
rm /home/yourusername/imoutofhere.sh
Then run it. :) Idea I'm trying to point out here is yeppers if someone were to want to run a script and have it remove itself as it's final act of valor ... Then just include the command to do that as the last line in it, as shown above. Note: Keep a copy of these to play with ie: imoutofhere.sh.bak cause these babies are going fast, errrr or you'll end up having to type them out again anyway. :D
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.

#29 Post by Deb-fan »

Hi and welcome to a new episode of dorking with bash scripts. :D

I have a thrilling and could be useful script/trick for people. You'll have to install the package espeak from the Debian repositories for it to work. There's also a newer version of the thing "espeak-ng" which stands for next generation I believe. I'm using plain ole espeak though. Was messing around with some simple ways to setup notifications, can definitely come in handy. Will be cooking something, set the stove timer and then wander into my room where I may promptly forget about it, then may or not hear the annoying beeps from the timer when it goes off. Since I'm getting old, helps to be able to set a quick reminder and have it interupt the movie or whatever I'm doing and remind me chow's almost done. :)

Per usual, create a file somewhere, I chose my users home directory and named it msg.sh, make it executable per usual again "chmod +x msg.sh" Here's the contents of the script.

Code: Select all

#!/bin/bash

read -p " # Please enter amount of time until notification, 15s = 15secs, 10m = 10 minutes etc. Read \"man sleep\" (the manual page for the sleep command ) to see possible time values you can use here. " TIME
echo
read -p " # Enter your notification message, some text to remind youself of what you wanted to do. " MSG # The message espeak will recite.

sleep $TIME && espeak "$MSG" &exit
Self explanatory but that's what it does, you run the script in terminal, it asks how long you want to set the wait time until notification and what you want the computer to say, enter this info, the terminal closes and WHAMO ... However long later it'll do it.

Edit: I recommend using the following message content to test this out.
You are the most attractive and intelligent specimen of humanhood I have ever seen ... WOW, just WOW
Awwww shucks computer, you say the nicest ( and truest) things. Thanks, I'm sort of fond of you too. Who's a good widdle debianbox, you are computer, yes you are, why yes you are. :P
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.

#30 Post by Deb-fan »

Okay yeppers here we go again, this one goes out to @CwF and right now inclined to think his username stands for Come-on-man w-haaaaa de-F**k .. :D

Anyway, you-@CwF introduced an interesting idea in a trainwreck of a how-to exchange. The autologin + startx without a display manager madness. That being I hadn't considered that it could be used in the way he applied it, logging in multiple users on different tty's(gettys.) automatically. Do think it's a cool idea and so started dorking around and here's some of the results of said dorking ...

I switched over myself to the full method employed in the Gentoo wiki, works great, not that it's technically superior in any way to how it's advised in the Archwiki, nor the bastardized version of the topic I put up originally, which was a mixture of ripping off the Gentoo wiki and some snagged and tested line to automatically startx in .profile. Did so mostly to be different. From everything I've ever seen and have played with all of them, all work fine, can even mix + match the things, all accomplish the same thing. Autologin/startx no display manager.

At this point ... then thought while I'm being different why not endeavor to be even more different. Removed the line to startx from my users .profile file and cooked this nonsense up. Created a script in my usual preferred place, which is still /home/myusername/.bin/startx.sh , yep ... named it startx.sh. Make the thing executable with the usual "chmod +x startx.sh" and here's the contents of it.

Code: Select all

#!/bin/bash

echo
echo
read -n1 -p " To startx press 1 or any key to continue with command-line session. " XORG

if [[ $XORG =~ ^[1]$ ]]; then
    [ "$(tty)" = "/dev/tty1" ] && exec startx
fi

echo
echo
Note: The above there is for tty1, if you were trying to autologin your user or other user accts you've setup on different/other tty's on your system, then yes ... change that as needed.

Added this line to the .profile file in my users home directory. To run a script when my user is logged into the OS. Just add it to the bottom of the file or you can wedge it in somewhere else, really doesn't matter as long as you don't screw up any of the other contents of the file, kay ? Don't copy and paste pieces over other crap in the file, delete stuff from it etc so forth. Anyway added the below to .profile.

Code: Select all

# Running a script at user login.
/home/myusername/.bin/startx.sh # That's the path to the dang script.
Which is what this does, when I boot-up the OS, my user is automatically logged into tty1 and when the .profile file gets sourced it runs that script. What it does is show me that dialogue in the script, the Press 1 to startx etc etc. If I press the number 1 key, that's what it does, starts Openbox for me, if I press any other key, keeps going in a command-line session, at any point I could just type "startx" to launch Openbox or another windows manager or desktop etc. So I got this all setup, rebooted and joy to the world, was greeted with my script asking me to press 1 if I wanted to startx, which I did, Openbox fired up and thought okay, now were/I'm getting somewhere, heel yeah! Opened a terminal typed "openbox --exit" to kill the X session and ? Nope, normal user prompt, because it's not a damn login shell, my wonderous bashy goodness didn't run and at this point decided screw this, it's time to whip out the big hammer.

Created a script at the following location, do this as root or with sudo privileges and I named it logout.sh, /usr/local/bin/logout.sh and added it to a file I have in /etc/sudoers.d/myfile I've discussed this before, very likely in this thread if not in one of the other monsters so not covering it again. If anyone is left with any doubts do not hesitate to enlist the help of google on the topic of how to add a script to a file in sudoers.d so that someone can run sudo commands + scripts-etc with sudo commands without having to enter a password.

That's what I did, in the file I added the path to the script /usr/local/bin/logout.sh at that point I can run that script using "sudo /usr/local/bin/logout.sh" in keybinds, panel launchers, terminals, menu entries etc etc without having to enter a password. Here's the contents of the logout.sh script.

Code: Select all

#!/bin/bash

pkill -KILL -u myusername

What the above does is kill off my user, smashes all processes, logs my user off and because things are setup to automatically log my user into that tty = tty1 here, as described in either of the autologin/startx no display manager how-to's found in tips/tricks section, my user is re-logged back into tty1 and I'm greeted with a fresh login shell and my beautiful scripty friend asking me to press 1 for X or any key for etc. In my case I'm using the windows manager Openbox and so added a custom keybind(key-combo)to run the script when pressed. Any and every Desktop or WM on planet earth should have an easy way to define custom keyboard shortcuts = keybinds, as noted using "sudo /usr/local/bin/logout.sh" in plenty of other stuff or all of them can also be used to run the script too, no password necessary. Here's the Openbox rc.xml file entry I'm using to run the script, when I press Alt + F9.

Code: Select all

    <keybind key="A-F9">
      <action name="Execute">
        <startupnotify>
          <enabled>true</enabled>
          <name>force-logout</name>
        </startupnotify>
        <command>sudo /usr/local/bin/logout.sh</command>
      </action>
    </keybind>
So basically I've taken the automatically startx part out of things, clearly very simple to put it back, in my case I'll just remove the comments = # these things from in front of the lines to startx in the .profile file in users /home. Pretty much all this was done for the heel of it and think it's pretty cool, shrugs. Not much difference, if I want to log into a graphical desktop-etc I have to press one key at boot and there you have it folks. :D
FOOTNOTES: Other observations about this, if you did have it setup so that your or whatever other users are automatically logged into whichever tty's on the system, going further ... If you wanted to have a bunch of GUI apps run when that user starts X. Could just add those as .desktop files (in @CwF's case he's wanting to launch web-browser), could also run additional scripts this way too or by adding whatever apps or scripts you want to run when user starts X in Openbox or Fluxbox's autostart files. Other desktops should have similar functionality but what's outlined ... using .desktop files would work fine too. In others words just using the same methods to autostart or run stuff as a person would in any graphical session.

Another dorkish thing was thinking on this. If someone were going for super-secret, as follows but to me it looks ugly/sloppy. Just leaving the prompt empty, so someone only gets a flashing prompt. Rather than giving instructions on press this or that.

Code: Select all

#!/bin/bash

read  -n1 -p " " XORG

if [[ $XORG =~ ^[1]$ ]]; then
    [ "$(tty)" = "/dev/tty1" ] && exec startx
fi
Last edited by Deb-fan on 2021-01-19 23:36, edited 5 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.

#31 Post by Deb-fan »

Had to trash this, as was going to add junk to it, went to dork with it to confirm something and nopers, wasn't right, so getting rid of what was here until such time as (if) I get around to debugging. :)

Alrighty got it sorted, had to poke the syntax used in the if statement a bit. Was going for a password protect kind of setup used along with what's in the last post. That being when someone is following one of the tutes on autologin/startx(on tty1)without a display manager. Noted that I fiddled with things a bit, so it's just autologin without a display manager and using a script run on user login to prompt whether or not to start a graphical session. This is an example using a password protected prompt instead.

Code: Select all

#!/bin/bash

echo
echo
read -sn5 -p " Enter access code or pass-phrase. " XORG

if [ $XORG -eq 12345  ]; then
    [ "$(tty)" = "/dev/tty1" ] && exec startx

else

echo " Let's see some ID !! WHO ARE YOU, WHERE DO YOU COME FROM ... WHAT DO YOU WANT TO DO WITH YOUR LIFE ?!?! "

fi

echo
echo
Quick explanation of that stuff. the -s is for silent so what someone types on the prompt isn't visible to whoever may be watching you, the n5 just means that bash reads the first 5 characters typed and stores them in a variable named XORG, IF what a user enters matches ( is equal/-eq to 12345, my super-secret password example here)the value of the XORG variable in the if statement, then it runs the following line starting the graphical session. Though if what the person enters doesn't match, is not -eq to 12345, runs the other command, echo's "Let's see some ID etc."

Yeppers that could be a lot of other things folks. Use your imagination ... that's what it's for. :)
Last edited by Deb-fan on 2021-01-20 04:11, edited 4 times in total.
Most powerful FREE tech-support tool on the planet * HERE. *

vmclark
Posts: 184
Joined: 2008-07-30 15:16

Re: Some good bash and bash alias tricks.

#32 Post by vmclark »

[quote="Head_on_a_Stick"]Here's a version that uses whiptail for a similar effect:
quote]zenity is another one of those menu thingy's

Code: Select all

#!/bin/bash -
# demonstrates all zenity functions
# also demonstrates
#+ FUNCNEST Limiting recursion
#+ lower casing ${selection,,}
#+ removing spaces ${choice// }
#+ file_selection with starting directory
#+ readlink to get final destination
#+ brief option to file (-b)

finale(){
  # demo - shows zenity return value(s)
  zenity --info \
    --title="Zenity returned:" \
    --window-icon=/usr/share/icons/gnome/22x22/emotes/face-worried.png \
    --width=400 \
    --text="$@"
  [ $? -eq 1 ] && exit 0
}

calendar(){
  result=$( \
    zenity --calendar \
	--title="Calendar demo" \
	--date-format="%A, %B %-d, %Y" \
  )
  [ $? -eq 1 ] && exit 0
  finale "$result"
}

entry1(){
  result=$( \
    zenity --entry \
      --title="Entry demo (visible)" \
      --text="Text entry dialogue" \
      --width=400 \
      --entry-text="This sentence can be changed." \
  )
  [ $? -eq 1 ] && exit 0
  finale "$result"
}

entry2(){
  result=$( \
    zenity --entry \
      --title="Entry demo 2 (invisible)" \
      --hide-text \
      --text="Text entry dialogue" \
      --width=400 \
      --entry-text="This sentence can be changed." \
  )
  [ $? -eq 1 ] && exit 0
  finale "$result"
}

error(){
  zenity --error \
    --title="Error demo" \
    --text="This is a sample error message"
  [ $? -eq 1 ] && exit 0
}

fileselection(){
  # --filename=FILENAME --multiple --directory --save --separator=SEPARATOR --confirm-overwrite --file-filter=NAME | PATTERN1 PATTERN2
  result=$( \
    zenity --file-selection \
      --title "File selection demo" \
      --filename=/etc/ \
  )
  [ $? -eq 1 ] && exit 0
  if [ -h $result ]; then
    reallink=$(readlink -f $result)
    txt=$(file -b $reallink)
    finale "$result\nbut this is a symbolic link to\n$reallink\nwhich is $txt)"
  else
    finale "$(file $result)"
  fi
}

info(){
  zenity --info \
    --title="Info demo" \
    --width=400 \
    --text="This is info text"
  [ $? -eq 1 ] && exit 0
}

list(){
  finale "This demo is using the list type with radio buttons\nThis next will show a check list"
  selection=$( \
    zenity --list \
      --title="Zenity Demonstration" \
      --width=640 --height=480 \
      --text="List type wih check boxes" \
      --column="Col 1" --checklist \
      --column "Item" \
        TRUE Oranges \
        TRUE Bananas \
        FALSE Cherios \
        FALSE Cigarettes \
  )
  [ $? -eq 1 ] && exit 0
  finale "$selection"
}

notification(){
  echo "message:You have been notified. The rest is up to you" | zenity --notification --listen --timeout 1
  [ $? -eq 1 ] && exit 0
}

progress(){
  (for i in $(seq 0 10 100);do echo "# $i percent complete";echo $i;sleep 1;done) | zenity --progress  --title="Progress demo" --width=800
  [ $? -eq 1 ] && exit 0
}

question(){
  zenity --question \
    --title="Question demo" \
    --text="Ready to proceed?" \
    --ok-label="I'll be careful" \
    --cancel-label="Get me out of here"
  [ $? -eq 1 ] && exit 0
}

textinfo1(){
  FILE=~/.bashrc
  zenity --text-info \
    --title="Text info demo" \
    --width 640 --height 480 \
    --filename=$FILE \
    --checkbox="This is acceptable."
  [ $? -eq 1 ] && exit 0
  finale "You accepted"  
}

textinfo2(){
  FILE=~/.bashrc
  zenity --text-info \
    --title="Text info demo" \
    --width 640 --height 480 \
    --filename=$FILE
  [ $? -eq 1 ] && exit 0
  finale "You accepted"  
}

warning(){
  zenity --warning \
    --title="Warning demo" \
    --width=400 \
    --text="This is a demo warning"
  [ $? -eq 1 ] && exit 0
}

scale1(){
  result=$( \
  zenity --scale \
    --title="Scale demo" \
    --text="How old are you")
  [ $? -eq 1 ] && exit 0
  finale "$result"
}

scale2(){
  result=$( \
    zenity --scale \
      --title="Scale demo" \
      --print-partial \
      --text="How old are you" \
  )
  [ $? -eq 1 ] && exit 0
  finale "$result"
}

scale3(){
  result=$( \
    zenity --scale \
      --title="Scale demo" \
      --value=50 \
      --max-value=450 \
      --min-value=50 \
      --step=5 \
      --text="Your aproximate weight" \
  )
  [ $? -eq 1 ] && exit 0
  finale "$result"
}

colorselection1(){
  TITLE="Color selection 1"
  result=$( \
    zenity --color-selection \
      --title="$TITLE" \
      --color="#123456")
  [ $? -eq 1 ] && exit 0
  finale "$result"
}

colorselection2(){
  TITLE="Color selection 2 with palette"
  result=$( \
    zenity --color-selection \
      --title="$TITLE" \
      --show-palette \
      --color="#123456" \
  )
  [ $? -eq 1 ] && exit 0
  finale "$result"
}

password(){
  result=$( \
    zenity --password \
      --title="Password demo" \
      --username)
  [ $? -eq 1 ] && exit 0
  finale "$result"
}

forms(){
  result=$( \
    zenity --forms \
      --title="Forms demo" \
      --text="Please fill out this form" \
      --add-entry=Name \
      --add-entry="Street Address" \
      --add-entry=City \
      --add-entry=State \
      --add-entry=Zip \
      --add-password=Password \
      --add-calendar="Date of birth" \
      --forms-date-format="%A, %B %-d, %Y" \
  )
  [ $? -eq 1 ] && exit 0
  finale "$result"
}

declare -r FUNCNEST=2

while :;do
  selection=$( \
    # Column 1 is a radio button or a checkbox and is pre-selected if TRUE
    # Column 2 is demo function name and is hidden from list
    zenity --list \
      --radiolist \
      --title="Zenity Demonstration" \
      --width=800 --height=600 \
      --text="Dialogue Type" \
        --column="Select" \
        --column="Hidden" \
        --column="Option" \
        --column="Description" \
        --hide-column=2 \
	  FALSE Calendar "calendar" "Choose a date - mm/dd/yyyy, mm/today/yyyy uses strftime"\
          FALSE "Entry 1" entry "Enter/Edit some text. (Visible)" \
          FALSE "Entry 2" entry "Enter/Edit some text. (Invisible)" \
          FALSE Error error "Show a error message" \
          FALSE "File Selection" file-selection "Select file(s) from fm type dialogue." \
          FALSE Info info "Show an information dialgoue" \
          FALSE List list "Radio buttons (This demo) and checkboxes" \
          FALSE Notification notification "Unfortunately influenced by Gnome-3" \
          FALSE Progress progress "Process % progress bar" \
          FALSE Question question "Ask question with OK and Cancel buttons" \
          FALSE "Text info 1" text-info "Display text file contents with checkbox" \
          FALSE "Text info 2" text-info "Display text file contents without checkbox" \
          FALSE Warning warning "Display a warning message " \
          FALSE "Scale 1" scale "Choose a number using bar slider - Returns final value" \
          FALSE "Scale 2" scale "Choose a number using bar slider - Returns all values" \
          FALSE "Scale 3" scale "Choose a number using bar slider - Step 5 (with arrow, not mouse)" \
          FALSE "Color Selection 1" color-selection "Select a color" \
          FALSE "Color Selection 2" color-selection "Select a color - shows palette" \
          FALSE Password password "Enter a Username and Password. Note: --width option doesn't work" \
          FALSE Forms forms "Display a data entry form" \
  )
  [ $? -eq 0 ] || exit 0
  choice=${selection,,}	# lowercase all
  ${choice// }		# eliminate all spaces
done

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.

#33 Post by Head_on_a_Stick »

Yes, zenity rocks but you can't use it from a console screen, unlike whiptail.
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.

#34 Post by Deb-fan »

Yeah that'd have to be a deal breaker for what I'd been thinking. Well maybe, guess it's how someone chooses to apply it, zenity could actually work(seen people use it and yeppers agree it can be pretty), so thanks regardless. Would be less portable than what I'd been intending this for. Was mostly shooting for a here's a script, if you've got bash and the basic cmds/pkgs almost everything Nix on the planet includes out-of-box, good to go. Of course when I said somebody should do xy and z things, polish it all up into a so easy a caveman can do/use it script, meant somebody other than me. :P

Not familiar with whiptail or zenity either. Dumped a lot of time into polishing up a chroot.sh script, expanding on it to include a bunch of other stuff/related options. Between it and the cleanup.sh the scripts have ended up being just under 200 lines and somewhere around 35hrs invested by this point. Hit burn-out so shelved the idea for now.

Don't know if I'll ever get the thing finished, are still things I want to add, adjust or areas I haven't managed to work out effective solutions to address junk, at least to a point where I'm satisfied with how the final product would work. For now it's going back on the 2-dork list and likely end up circling back to it at some point in future. Mostly seems to have ended up being one of those CHIT, come too far to abandon things now situations. About formatting imo, at least for what I've got in mind here I actually like the raw command-line look. Think the main thing is that the dialogue clearly/effectively conveys what's going on, what options the user has, what to enter or press to make selections, at this or that point while the script is doing it's job.

Same for formatting and layout, using echo for blank/new lines = spacing. Making sure text isn't squished together or stretched out too much so it doesn't look ugly or weird. I seem to have settled on using capitals in this junk for emphasis added, important notices, warnings or things I want the user to be aware of and consider more closely. That's just falling back on long standing internet communication conventions/traditions, far as I'm aware capitalizing text has always been considered the equivalent of someone yelling.

So it's common sense when you see something in caps in something like a chroot script to understand it may be important. A user may want to pay attention to what's going on. Anyway that's what I've settled on in the (if it ever gets done) chroot.sh project. Pleased with some stuff, always room for improvement or enhancements and still don't think it's ready for prime time atm.
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.

#35 Post by Deb-fan »

Wanted to post a quick enhancement to the notification trick in a previous post. New and improved so that a terminal, in this case terminator will also pop up and display whatever reminder someone has set, in addition to espeak saying it. Could be easy to be out of room or doing something and just not notice a persons pc chirping out a helpful reminder.

So I created another script in my preferred location again that's still /home/myuser/.bin and named it msg2.sh. Added that .bin directory to my users path to make running the thing easier. There's a line already in users home .profile file to add bin if it exists, had to create the .bin directory and add one .(dot) here in the .profile file.

Code: Select all

# set PATH so it includes user's private bin if it exists # Modded to cover my preference .bin
if [ -d "$HOME/.bin" ] ; then
    PATH="$HOME/.bin:$PATH"
fi 


Make the script executable per usual with chmod +x etc and here's the contents.

Code: Select all

#!/bin/bash

read -p " # Please enter amount of time until notification, 15s = 15secs, 10m = 10 minutes etc. Read \"man sleep\" (the manual page for the sleep command ) to see possible time values you can use here. " TIME
echo
read -p " # Enter notification message, some text to remind youself of what you wanted to do. " MSG # The message espeak will recite.

sleep $TIME && espeak "$MSG" && sleep 1s && terminator -e "echo $MSG ; $SHELL" &exit 
Same deal as before you run the script in terminal, set a time, enter what you want espeak to say and what message someone wants displayed in terminator. The terminal closes and when that time has elapsed, espeak makes its announcement and the terminal pops up with the set text displayed.

Noticed for several terminals in this kind of thing the secret sauce to getting the terminal to remain open was using that ; $SHELL part in the script. Though read the manpage for your terminal of choice. Shouldn't take much fiddling to figure it out.

ps, Though it's really still just more dorking with bash/scripts, it's a beast, not even sure there was room enough here ... So gave this monster its own thread. Alright folks ... have a good dy/nt and happy Debian'ing. :)
Most powerful FREE tech-support tool on the planet * HERE. *

User avatar
craigevil
Posts: 5256
Joined: 2006-09-17 03:17
Location: Oz
Has thanked: 2 times
Been thanked: 2 times

Re: Some good bash and bash alias tricks.

#36 Post by craigevil »

I don't have any useful bash scripts, but I do use alot of aliases.

Code: Select all

# Start gomuks Matrix Client
alias gomuks=/home/pi/Downloads/gomuks-linux-arm64

# Show open ports
alias ports='netstat -tulanp'

# Refresh .bashrc
alias bashrc="source ~/.bashrc"

# become root #
alias root='sudo -i'
alias su='sudo -i'


# if user is not root, pass all commands via sudo #
if [ $UID -ne 0 ]; then
alias update='sudo apt update'
alias ainstall='sudo apt install'
alias apurge='sudo apt purge -y --autoremove'
alias upgrade='sudo apt full-upgrade'
alias aremove='sudo apt autoremove -y'
alias reboot='sudo reboot'
alias shutdown="sudo shutdown -P now"
fi

# APT User Commands
alias asearch='apt search'
alias afile='apt-file search'
alias apolicy='apt policy'
alias show="apt show"

# Handy-dandy aliases for journalctl and systemctl
alias jc='sudo journalctl -b'
alias jca='sudo journalctl'
alias jcf='sudo journalctl -f'
alias jcr='sudo journalctl --list-boots'
alias sc='sudo systemctl'

# Making files immortal & executable
alias im+="sudo chattr +i"
alias im-="sudo chattr -i"
alias exe="sudo chmod +x"

# Create Python virtual environment
alias ve='python3 -m venv ./venv'
alias va='source ./venv/bin/activate'

# Ping Commands
# Stop after sending count ECHO_REQUEST packets #
alias ping='ping -c 5'
alias pg="ping google.com -c 5"

# alias shortcuts
alias raspi="sudo raspi-config"
alias clr="clear"
alias clrh="history -c -w ~/.bash_history"
alias df='df -H'
alias du='du -ch'
alias mk="mkdir -p"
alias loading="sudo dmesg > ~/dmesg.txt"
alias edit='nano'
alias pico='nano'
alias notepad='pluma'
alias gedit='pluma'

# ls Commands
## Colorize the ls output and human readable sizes ##
alias ls='ls --color=auto --human-readable -al'
## Use a long listing format ##
alias ll='ls -la'
## Show hidden files ##
alias l.='ls -d .* --color=auto'
# Listing files in folder
alias listkb="ls -l --block-size=K"
alias listmb="ls -l --block-size=M"

# Clipboard
alias cpy="xclip -selection clipboard"

# Calculator
alias bc="bc -l"

# Resume wget by default
alias wget="wget -c"

# ps Commands
alias ps="ps auxf"
# Get top process eating cpu
alias pscpu="ps auxf | sort -nr -k 3"
alias pscpu10="ps auxf | sort -nr -k 3 | head -10"
# Get top process eating memory
alias psmem='ps auxf | sort -nr -k 4'
alias psmem10='ps auxf | sort -nr -k 4 | head -10'

# Free and Used Ram
alias meminfo='free -l'
alias free='free -mt'

# Run top in alternate screen
alias top='tput smcup; top; tput rmcup'
Raspberry PI 400 Distro: Raspberry Pi OS (Unstable) Kernel: 5.10.52-v8+ aarch64 DE: MATE Ram 4GB
Debian - "If you can't apt install something, it isn't useful or doesn't exist"

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

Re: Some good bash and bash alias tricks.

#37 Post by bester69 »

It helps to catch permission without logging out

Code: Select all

alias updategroupermissions='exec su -l $USER'
bester69 wrote:You wont change my mind when I know Im right, Im not an ...

vmclark
Posts: 184
Joined: 2008-07-30 15:16

Re: Some good bash and bash alias tricks.

#38 Post by vmclark »

bester69 wrote:It helps to catch permission without logging out

Code: Select all

alias updategroupermissions='exec su -l $USER'
Typing "exec su -l $USER" would be easier than having to type "updategroupermissions", it would appear.

Post Reply