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.

#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: 5258
Joined: 2006-09-17 03:17
Location: Oz
Has thanked: 3 times
Been thanked: 3 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