You are not logged in.

#3051 2017-08-08 07:12:23

parchd
Member
Registered: 2014-03-08
Posts: 421

Re: Post your handy self made command line utilities

escondida wrote:

My alarm clock is annoying. It makes an annoying sound that my unconscious mind just wants to stop, so I tend to hit the snooze after partially waking up, but not enough to actually get up.

I'm familiar with the problem. Years ago, I attempted to solve it by writing my own alarm clock program for my Nokia N900. The alarm would go off with no option to snooze, and would only stop if I plugged the phone in. The charger was kept in a different room, so I had to get up and go to that other room, making it an extremely effective alarm clock. That is, until in a half-awake moment of ingenuity, I realised I could shut the damn thing up by removing the battery.

When I awoke feeling refreshed, hours after I should have been at work, I decided to abandon the project.

Offline

#3052 2017-08-09 15:03:58

escondida
Package Maintainer (PM)
Registered: 2008-04-03
Posts: 157

Re: Post your handy self made command line utilities

parchd wrote:
escondida wrote:

My alarm clock is annoying. It makes an annoying sound that my unconscious mind just wants to stop, so I tend to hit the snooze after partially waking up, but not enough to actually get up.

I'm familiar with the problem. Years ago, I attempted to solve it by writing my own alarm clock program for my Nokia N900. The alarm would go off with no option to snooze, and would only stop if I plugged the phone in. The charger was kept in a different room, so I had to get up and go to that other room, making it an extremely effective alarm clock. That is, until in a half-awake moment of ingenuity, I realised I could shut the damn thing up by removing the battery.

When I awoke feeling refreshed, hours after I should have been at work, I decided to abandon the project.

Ahhh, yes. I did a similar thing back when I had a cell phone. I'm trying not to read anything about human nature from the obvious desire of the unconscious mind to remain that way...

Offline

#3053 2017-08-09 15:07:16

ewaller
Administrator
From: Pasadena, CA
Registered: 2009-07-13
Posts: 20,200

Re: Post your handy self made command line utilities

parchd wrote:

Years ago, I attempted to solve it by writing my own alarm clock program for my Nokia N900. The alarm would go off with no option to snooze, and would only stop if I plugged the phone in. The charger was kept in a different room, so I had to get up and go to that other room, making it an extremely effective alarm clock. That is, until in a half-awake moment of ingenuity, I realised I could shut the damn thing up by removing the battery.

When I awoke feeling refreshed, hours after I should have been at work, I decided to abandon the project.

I like this solution out of MIT http://alumni.media.mit.edu/~nanda/projects/clocky.html


Nothing is too wonderful to be true, if it be consistent with the laws of nature -- Michael Faraday
Sometimes it is the people no one can imagine anything of who do the things no one can imagine. -- Alan Turing
---
How to Ask Questions the Smart Way

Offline

#3054 2017-08-16 05:55:55

Docbroke
Member
From: India
Registered: 2015-06-13
Posts: 1,437

Re: Post your handy self made command line utilities

This is wrapper around wit, (wbfs-manager for Wii). Wit is wonderful command-line tool but also quite confusing to use for beginners. This wrapper may make it easier.

#!/bin/bash

[ $(id -u) != 0 ] && echo "must run as root user" && exit
GAMEFOLDER="/home/sharad/games/wii/"

echo -n "Choose?
    l) list games in USB
    s) copy games to USB
    f) format USB to wbfs
    c) check USB for errors
    r) remove game from USB
    t) change game title in USB
    w) convert iso to wbfs

» "

read -n 1 ops

case $ops in
    l)  wwt -a list ;; # /dev/sdb1 ;;
    s)  echo "Starttime: $(date +%r)"
        wwt -a add --source $GAMEFOLDER -v -u ;;    #-p /dev/sdb1 ;;
    f)  lsblk
        echo "select drive to format"
        read drive
        echo "formating $drive, press ^c in 10 seconds to stop" && sleep 10
        wwt format -v --force $drive ;;
    c)  echo -e " Choose file to check
            $(ls $GAMEFOLDER)
            drive"
        read target
        case $target in
            drive) wwt -a check -v ;; # /dev/sdb1 
            *) wwt -v check $GAMEFOLDER/$target ;;
        esac
        ;;
    r)  wwt -a list
        echo "choose disk to remove"
        read disk
        wwt -a -v remove "$disk" ;; #-p /dev/sdb1 ;;
    t)  wwt -a list
        echo "choose title id to change"
        read id
        echo "provide new title"
        read -a title
        wwt -a settitle "$id"="${title[@]}" ;; #-p /dev/sdb1 ;;
    w)  echo "choose iso file to convert, (dont write .iso in the file name)"
        read iso
        wit copy --source "$iso".iso --wbfs -d "$iso".wbfs -v
esac

Offline

#3055 2017-08-25 16:50:20

qinohe
Member
From: Netherlands
Registered: 2012-06-20
Posts: 1,494

Re: Post your handy self made command line utilities

I was in need of a count down timer with variable endtime and able to reboot or poweroff then continue the count and reset by user if neccesary.
Though it really works well, any chance the main script can be simplified?
The counter is started with a systemd timer
lapse.timer

[Unit]
Description=Runs lapse every minute

[Timer]
OnBootSec=1min
OnUnitActiveSec=1min
Unit=lapse@mark.service

[Install]
WantedBy=multi-user.target

Which starts a user service every N min.
lapse@.service

[Unit]
Description=time lapsed
ConditionPathExists=/home/mark/bin/lapse

[Service]
Type=simple
User=%I
ExecStart=/home/mark/bin/lapse run 
WorkingDirectory=/home/%I/

Which starts the following script
lapse

#!/bin/bash
#set -x
begin=24000
end=2000
boottime=120
path=~/bin

starttime="$path"/data/starttime
delta="$path"/data/delta
diff="$path"/data/diff
inter="$path"/data/inter
past="$path"/data/past
boot="$path"/data/boot
date=$(date)
now=$(date +%s)


if [[ $1 == run ]]; then
  while [[ ! -f $starttime ]]; do
    mkdir -p "$path"/data
    touch "$starttime" "$delta" "$diff" "$inter" "$past" "$boot"
  done

  if [[ -s $starttime ]]; then
    bc -q <<< "$now - $(<"$past")" > "$diff"

    if [[ $(<"$diff") -lt 200 ]]; then
      bc -q <<< "$(<"$delta") - $(<"$diff")" > "$inter"
    else
      bc -q <<< "$(<"$delta") - $boottime" > "$inter"
    fi  

    cp "$inter" "$delta"
    printf "$now %s\n" > "$past"
  else
    printf "$date %s\n"  > "$starttime"
    printf "$now %s\n" > "$past"
    printf "$begin %s\n" > "$delta"
  fi  

  if [[ $(<"$delta") -lt $end ]]; then
    truncate -s 0  "$starttime" "$delta" "$diff" "$inter" "$past" "$boot"
    sudo poweroff
  fi  

elif [[ $1 == reset ]]; then
  truncate -s 0 "$starttime" "$delta" "$diff" "$inter" "$past" "$boot"

elif [[ $1 == ck ]]; then
  printf "Count was started: %s\n"  "$(<"$starttime")"

  if [[ $(<"$boot") = 0 ]]; then 
    printf "Last boot was: reboot \n"
  elif [[ $(<"$boot") = 1 ]]; then
    printf "Last boot was: poweroff \n"
  else
    printf "Not booted since count started \n"
  fi

  printf "Seconds last count: %s\n" "$(<"$diff")"
  printf "Seconds left: %s\n" $(($(<"$delta")-end))
  printf "Remaining: %s\n" $((200*$(<"$delta")/begin % 2 + 100*$(<"$delta")/begin))%
  printf "Expected end of count: %s\n" "$(date -d @$(($(date +%s)+$(<"$delta")-end)))"
else
  printf "Usage: ./lapse ck or ./lapse reset \n"
fi

exit 0

This boot script tells me if the system was ever rebooted or had a poweroff with the check (ck) option.
boot

#!/bin/bash

mydir="$(dirname "$(readlink -f "$0")")"
past="$mydir"/data/past
boot="$mydir"/data/boot

  if [[ $1 == reboot ]]; then
    echo '0' > "$boot"
    sudo reboot
  
  elif [[ $1 == poweroff ]]; then
    echo '1' > "$boot"
    sudo poweroff
  fi  

exit 0

Offline

#3056 2017-09-02 23:02:27

snakeroot
Member
Registered: 2012-10-06
Posts: 168

Re: Post your handy self made command line utilities

There are Arch users who religiously check the archlinux.org home page before each update to make sure there's no special instructions to say, prevent them borking Perl.

This update wrapper is not for them. For the rest of us, however . . . .

#!/bin/bash
/usr/bin/ping -c 1 www.archlinux.org > /dev/null || { echo "archlinux.org is down. Aborting" && exit; }
ignore_db="AUR.db"
newest_db=$(ls -t -I ${ignore_db} /var/lib/pacman/sync | /usr/bin/head -n1)
newest_db_date=$(/usr/bin/stat /var/lib/pacman/sync/${newest_db} | /usr/bin/grep Modify | /usr/bin/sed s/Modify:\ //)
newest_db_date_utc=$(/usr/bin/date -u -d "${newest_db_date}" +%s)
newest_news_date=$(/usr/bin/curl -s --head https://www.archlinux.org/feeds/news/ | grep ^last-modified | sed -e s/^last-modified:\ //)
newest_news_date_utc=$(/usr/bin/date -u -d "${newest_news_date}" +%s)

if [[ $newest_news_date_utc -lt $newest_db_date_utc ]]; then
echo "There is no new news on the Arch homepage. Updating."
/usr/bin/sudo /usr/bin/pacman -Syu
else
echo "There is news on the Arch homepage. Please review it before updating."
/usr/bin/sudo /usr/bin/pacman -Sy
fi

Offline

#3057 2017-09-02 23:09:35

jasonwryan
Anarchist
From: .nz
Registered: 2009-05-09
Posts: 30,424
Website

Re: Post your handy self made command line utilities

Don't pacman -Sy, it breaks things.


Arch + dwm   •   Mercurial repos  •   Surfraw

Registered Linux User #482438

Offline

#3058 2017-09-03 00:08:44

Trilby
Inspector Parrot
Registered: 2011-11-29
Posts: 30,330
Website

Re: Post your handy self made command line utilities

That's also an aweful lot of grep + sed + sed + sed + grep + variables + etc.
You might want to read stat's man page and see what the following does:

stat -c "%Y %n" /var/lib/pacman/sync/*

Then when you've trimmed that script down to a couple lines you may want to read curl's man page and see what the -z flag will do when you give it your database files (hint, curl can be told to grab the content of the url if and only if it is newer than the age of a file (or set of files) provided to the -z flag).  Then when you've trimmed it down to one line you'll have acheived perfection:

Perfection is achieved, not when there is nothing more to add, but when there is nothing left to take away.

Although I'm not sure the age of the .db files is really the date you want to check.  You can easily have updated and read the news more recently than the dbs being updated.

Last edited by Trilby (2017-09-03 00:13:27)


"UNIX is simple and coherent" - Dennis Ritchie; "GNU's Not Unix" - Richard Stallman

Offline

#3059 2017-09-08 06:21:09

ericbakuladavis
Member
Registered: 2017-08-27
Posts: 1

Re: Post your handy self made command line utilities

Here's a service/script that checks the battery level every minute and hibernates the computer if the battery is discharging and falls to 5% or below. It provides a pop-up window which gives the user the option to cancel the hibernation. This requires the xorg-xmessage package which is tiny and has only 2 dependencies.

/etc/systemd/system/battery-monitor.service

[Unit]
Description=Hibernates the system when the battery is low 

[Service]
Type=simple
Environment=DISPLAY=:0.0
Environment=XDG_RUNTIME_DIR=/run/user/1000
Environment=XAUTHORITY=/home/username/.Xauthority 
ExecStart=/usr/local/bin/battery-monitor

[Install]
WantedBy=multi-user.target

You'll want to substitute "username" with your username. On my system, the environment variables allow xmessage and systemctl hibernate to work properly. You may require different environment variables.

/usr/local/bin/battery-monitor

#!/bin/sh
cd /sys/class/power_supply/BAT1
while :
do
	if [[ $(cat capacity) -le 5 && $(cat status) == "Discharging" ]]
	then
		xmessage -center -buttons "Hibernate","Cancel Hibernation" -timeout 10 "Battery low - Going into hibernation..."
		if [ $? -ne 102 ] 
		then
			systemctl hibernate
		fi
	fi
	sleep 60
done

Your battery information may be at a different path.

Enable the service by running

# sysytemctl enable battery-monitor.service

I'm new to Arch Linux and scripting. Please share any feedback you may have.

Last edited by ericbakuladavis (2017-09-24 02:58:48)

Offline

#3060 2017-09-08 08:43:59

YesItsMe
Member
Registered: 2017-07-12
Posts: 37

Re: Post your handy self made command line utilities

I wrote a shell script in Common Lisp which can make RSS feeds from websites a while ago. Still adding small improvements every now and then. I hope it still fits this topic's rules (after all, you can just chmod +x it).

Last edited by YesItsMe (2017-09-08 08:56:14)

Offline

#3061 2017-09-08 08:51:30

parchd
Member
Registered: 2014-03-08
Posts: 421

Re: Post your handy self made command line utilities

YesItsMe wrote:

I wrote a shell script in Common Lisp

I don't think it is still a shell script if it isn't something used as a shell (sh/csh/bash/zsh/ksh...), I think it is just a script... unless there is a lispsh.

which can make RSS feeds from websites a while ago. Still adding small improvements every now and then.

Very useful! I've got a couple of scripts to do that, but I never thought of making it into something general instead of a script per website.

I hope it still fits this topic's rules (after all, you can just chmod +x it).

Why wouldn't it? It is a command line utility, and it definitely seems handy!

Offline

#3062 2017-09-08 08:55:40

YesItsMe
Member
Registered: 2017-07-12
Posts: 37

Re: Post your handy self made command line utilities

parchd wrote:
YesItsMe wrote:

I wrote a shell script in Common Lisp

I think it is just a script... unless there is a lispsh.

It is a script that can be run on the shell. :-D
To be precise, it is probably rather a REPL script, indeed. Sorry for the wording.

Offline

#3063 2017-09-22 04:07:49

Barkester
Member
Registered: 2017-07-01
Posts: 19

Re: Post your handy self made command line utilities

So much here is over my head, but learning alot. Just a cli user myself really. Enjoying the recursive renamer from a 2009 post and some other goodies, carefully copying each into vim rather than pasting to get the logic of them.

As a beginner, notes are real important to me as I forget parts that ain't bolted and I also needed to address my  self-inflicted clean-installs. (I chmoded the whole file system last time. Wasn't where I thought.)

This a a sorta personal help file. I made these aliases to make myself a little help page with the easy-to-remember name of clit for cli texts. Gives me all my notes in a lump and is grepable if I'm lazy to scan, but its meant to be small so I rarely do. I keep txts with common commands ( I still forget), a locals list for important file locations like configs,  a list of installed programs, a list of personal scripts with functions, Its all personal and constantly changing, hence the clitud alias. It  zips up my scripts and some config. files which I like to send a copy to Yandex.disk, no alias needed.

My studies are easier for it, so others may like them :

https://hastebin.com/iruyuqudec

Amazing how long this post has gone. 8 years a record?

edit: here's the same with little extra to make it pretty. Pretty sparten before so got to adding a delete to get rid of old stuff and went ahead and added clitbu to send a copy to the cloud. Downright pretty now, but still not really script worthy to my mind so in the bash it goes.

https://hastebin.com/esulisican

Everybody needs a hobby.

Last edited by Barkester (2017-09-22 08:41:37)

Offline

#3064 2017-09-22 15:32:53

escondida
Package Maintainer (PM)
Registered: 2008-04-03
Posts: 157

Re: Post your handy self made command line utilities

Yes, back-ups are *always* a good idea! (-:

You might find it helpful to keep your configs and such in git or a similar version control system; the main benefit over compressed back-ups is that your commit messages make your own li'l changelog, so if you wonder why you changed something, you can look back through the history to the old version of the file or take a look at the commit message.

Offline

#3065 2017-09-23 01:47:37

Barkester
Member
Registered: 2017-07-01
Posts: 19

Re: Post your handy self made command line utilities

Haven't yet had my first night out with git, but she sounds nice. Only really used it with clone up to now.

I'll hit the man on that one.

Offline

#3066 2017-09-23 18:13:31

dmerej
Member
From: Paris
Registered: 2016-04-09
Posts: 101
Website

Re: Post your handy self made command line utilities

Insert the most recent file in the current directory into the current command line, properly escaped when hitting 'alt-l':

(zsh only)

function latest() {
  echo $(\ls --quoting-style=shell -t | head -n1)
}

# Insert latest file in the current prompt
latest-file-widget () {
  LBUFFER="${LBUFFER} $(latest)"
  local ret=$?
  zle redisplay
  return $ret
}

zle -N latest-file-widget
bindkey '^[l' latest-file-widget

Responsible Coder, Python Fan, Rust enthusiast

Offline

#3067 2017-09-25 14:36:14

kokoko3k
Member
Registered: 2008-11-14
Posts: 2,420

Re: Post your handy self made command line utilities

Due to some bug lying in nvidia driver or maybe in the modesetting driver... or the whole systemd, i don't know, when Xorg configured with a "reverse prime" setup is closed, "/dev/dri/card1" is left opened by systemd; making impossible to unload nvidia_drm, making unpossible to unload other nvidia modules, making impossible to pass the gpu to the virtio domain.
I discovered that it is actually possible, probably dangerous, to manually close opened files by using gdb; now given that i think that that opened handle is a bug, because somebody forgot to close the file, i think it is safe to close it, assuming the code will not touch it anymore.
And indeed, it works, the system *seems* to work good.
(--EDIT--
Oh well, system is stable, but systemd freezed, so any systemctl command just hangs.)

Now in topic, i wrote a tool that given a filename (or part of it) searches for open handles and close the handle after a confirmation (pipe yes to it to automate):

#!/bin/bash

if [ "$#" != 1 ] ; then
	echo "Search which processes keep a given file open and optionally close the open handle."
	echo "Usage: $(basename $0) filename"
        echo "Or: yes > $(basename $0) filename" to close handles without confirmation"
	exit
fi

filename="$1"

for fd_path in /proc/*/fd/* ; do
	if readlink $fd_path | grep $filename 1>/dev/null ; then
		pid=$(cut -d "/" -f 3 <<< $fd_path)
		exe=/proc/$pid/cmdline
		fd=$(cut -d "/" -f 5 <<< $fd_path)
		echo
		echo "!! Found $(readlink $fd_path)."
		echo "   Held by $exe with pid $pid, fd: $fd."
		read -p "   Close it? Yy/Nn Ss/Nn:  " -n 1 -r
		if [[ $REPLY =~ ^[YySs]$ ]]
		then
			echo echo "   !! Deleting handle."
			gdb -batch -ex "attach $pid" -ex "p close($fd)"
				else
			echo ; echo "   Skipping."
		fi
		echo

	fi
done

Last edited by kokoko3k (2017-09-25 16:03:44)


Help me to improve ssh-rdp !
Retroarch User? Try my koko-aio shader !

Offline

#3068 2017-10-09 23:39:46

escondida
Package Maintainer (PM)
Registered: 2008-04-03
Posts: 157

Re: Post your handy self made command line utilities

Given the following addressbook layout in ~/notes/addressbook...

name: J. Random Friend
phone: 555.555.5555
email: jrand@test.com

name: Someone I. Talk-To
email: someone@test.com
phone: 555.555.5556
email: someone.other-address@test.com
address:
	555 Somewhere Specific Rd.
	Somewhere More General
	Somewhere Yet More General, Postal  Code

name: [...]

The following scripts I find to be very useful:

#!/usr/bin/env rc
# ~/local/bin/address: look up someone in my addressbook

ssam -n 'x/(.+\n)+/ g/'^$"*^'/ p' $home/notes/addressbook

That line noise uses ssam, the stream editor edition of plan9port's sam, to print out the entire stanza matching the script's arguments.

The following auxiliary mini-script can be used to get just the email(s); this works out of the box with mutt's address query function.

#!/usr/bin/env rc
# ~/local/bin/getemail: get email addresses
# TODO: give this a better name

address $* | awk '/email/ {print $2}'

Who needs a whole addressbook program?

Share & enjoy.

Offline

#3069 2017-10-10 00:31:58

Trilby
Inspector Parrot
Registered: 2011-11-29
Posts: 30,330
Website

Re: Post your handy self made command line utilities

You can do the same with sed:

sed -n '/^$/bC; H; $bC; b; :C x; /'"$*"/p' /path/to/addressbook

And the email extraction without need for piping through another tool:

sed -n '/^$/bC;H;$bC;b;:C x;/'"$*"'/s/.*email: \([^\n]*\).*/\1/p' /path/to/addressbook

The commented expansion of the second sed script:

# Blank line / end of a stanza, branch to "C" (for "check")
/^$/ bC
# Otherwise append the line to the hold buffer
H
# At the end of the file branch to "C" just like an empty line / end of stanza
$ bC
# Any other line, branch to end (e.g. skip "C" block)
b
# "C" check block, retrieve hold buffer
:C
x
# On buffers (i.e., stanzas) matching a search term,
#   remove everything but a string between "email: " and a newline
#   and print what remains
/SEARCHSTRING/ s/.*email: \([^\n]*\).*/\1/p

Last edited by Trilby (2017-10-10 00:41:58)


"UNIX is simple and coherent" - Dennis Ritchie; "GNU's Not Unix" - Richard Stallman

Offline

#3070 2017-10-10 02:07:56

escondida
Package Maintainer (PM)
Registered: 2008-04-03
Posts: 157

Re: Post your handy self made command line utilities

That's really neat, Trilby! To be honest, I've never learned sed's more advanced features, like branching. Now I'm thinking perhaps I should.

Offline

#3071 2017-10-11 17:31:09

IrvineHimself
Member
From: Scotland
Registered: 2016-08-21
Posts: 275

Re: Post your handy self made command line utilities

With the increasing number of profiles in /etc/firejail, it is very difficult to know if you are utilising the available profiles to their full advantage. I wrote this shell to check the installed profiles against what is installed to /usr/bin.

#!/bin/bash
# Shell to find unused Firejail profiles

 ### Colours
Blu=$'\e[1;34m' # Blue
Cyn=$'\e[1;36m' # Cyan
Dimd=$'\e[2m'   # Dimmed
Ulnd=$'\e[4m'   # Underlined
End=$'\e[0m'    # Reset
 ### End colours

 ### Paths
EtcFirejail="/etc/firejail"
LocalBin="/usr/local/bin"
 ### End paths

 ### Prompts
PrmptMsg1="Create firejail /usr/local/bin symlinks? y/n"
PrmptMsg2="Enter profile name, null string to terminate"
 ### End prompts

 ### ### ### Start Main ### ### ###
printf '%-50s%-50s\n' ${Dimd}${Ulnd}"PROFILE NAME"${End} ${Dimd}${Ulnd}"OWNER'S NAME"${End}
ls "$EtcFirejail" | grep "profile" |\
    while read Line ; do
        ProfileName=${Line%%.profile}
        ### Use pacman to check if bin file exists
        Owner=$(pacman -Qoq /usr/bin/$ProfileName 2>/dev/null)
        ### StndError is redirected to /dev/null, so if owner is not a nullstring,
        ### then its a usefull profile
        if [[ ! "$Owner" = "" ]] ; then
            # Silently check if profile is symlinked to firejail  in /usr/local/bin
            if ! ls "$LocalBin" | grep "$ProfileName" 1>/dev/null ; then
                printf '%-50s%-50s\n' ${Grn}"$ProfileName"${End} ${Blu}"$Owner"${End}
            fi
        fi
    done
 ### Option to create symlinks
echo "$PrmptMsg1"
read -n1 -s Key
if  echo "$Key" | grep -iq "y" ; then
    Target="Dummy"
    until [[ "$Target" = "" ]] ; do
        echo "$PrmptMsg2"
        read Target
        if [[ ! "$Target" = "" ]] ; then
            sudo ln -s /usr/bin/firejail /usr/local/bin/"$Target"
        fi
    done
fi

It works by checking all the profiles in /etc/firejail against pacman -Qoq /usr/bin/$ProfileName to find the owner. If the file doesn't exist, it returns a null string. On the other hand, if the file does exist, it checks /usr/local/bin to see if the profile has been symlinked.

Finally, it offers the opportunity to actually create the missing symlinks. (This last should be used with care and forethought!)

Supplement: To check what profiles have actually been symlinked, you can use:

#!/bin/bash
# Lists symlinked Firejail profiles

 ### Colours
Cyn=$'\e[1;36m' # Cyan
Dimd=$'\e[2m'   # Dimmed
End=$'\e[0m'    # Reset
 ### End colours

 ### Start Main
echo -e ${Dimd}"The following firejail profiles have been symlinked:"${End}${Cyn}
ls -la /usr/local/bin | grep "\->"| grep "/usr/bin/firejail" | cut -d':' -f2 | cut -d' ' -f2 | column -x
printf ${End}

Edited to change "owner doesn't exist" to "file doesn't exist"

Last edited by IrvineHimself (2017-10-11 17:38:44)


Et voilà, elle arrive. La pièce, le sous, peut-être qu'il arrive avec vous!

Offline

#3072 2017-10-13 12:40:52

Stencon281
Member
Registered: 2016-09-21
Posts: 40

Re: Post your handy self made command line utilities

Here's something I wrote that lets me navigate between directories without much fuss.

Each time I type 'md' it will write the current working directory into the file at $MARKEDPATH

Whenever I type 'lsmp' it will display all the paths I've marked by line number.

1 /home/foo/documents
2 /home/foo/pictures
3 /home/foo/music
4 /home/foo/work
5 /home/foo/bar

line 1 is always the most recently added path and where the 'ed' command will take you if you call it with no arguments.

navigating to /home/foo/pictures is 'ed 2'
navigating to /home/foo/music is 'ed 3'

etc....

# mark directory and cd into it from any other shell
function md {
    if [[ "$#" -eq 0 ]]; then
		cwd=$(pwd)
        echo $cwd &>> $MARKEDPATH
		export CURRMD=$cwd
    else
        echo $1 &>> $MARKEDPATH
		export CURRMD=$1
    fi
}

# enter marked directory, enter most recent marked path by default
function ed {

	index="$(lc $MARKEDPATH | linesplit ' ')p"

	if [[ "$#" -eq 1 ]]; then
		index="$1""p"
	fi

	markpath=$(tac "$MARKEDPATH" | sed -n "$index")

    if [ -z "$markpath" ]; then
    	echo "no mark directory set"
    else
		cd "$markpath"
    fi
}

# count number of lines
function lc {
	wc -l "$1"
}

# split at delimiter
function linesplit {
	cut -d "$1" -f 1
}

# show marked paths
function lsmp {
	tac $MARKEDPATH | cat -n
}

Now the real question is.... how to get this to work with zsh autocomplete?

Offline

#3073 2017-10-13 12:48:59

Trilby
Inspector Parrot
Registered: 2011-11-29
Posts: 30,330
Website

Re: Post your handy self made command line utilities

Stencon, you just more or less reimplemented pushd, popd, and dirs.  You'd probably be better off just using those (you also masked the name of the one true text editor making it unusable).

Also as pushd/popd/dirs are shell builtins (in bash and zsh) completion will work "out of the box".

Last edited by Trilby (2017-10-13 12:50:29)


"UNIX is simple and coherent" - Dennis Ritchie; "GNU's Not Unix" - Richard Stallman

Offline

#3074 2017-10-13 13:15:27

Stencon281
Member
Registered: 2016-09-21
Posts: 40

Re: Post your handy self made command line utilities

Trilby wrote:

you also masked the name of the one true text editor making it unusable.

What do you mean by this?

Also, I did not know about those commands I will check them out.

Offline

#3075 2017-10-13 13:19:05

Trilby
Inspector Parrot
Registered: 2011-11-29
Posts: 30,330
Website

Re: Post your handy self made command line utilities

Mostly a joke.


"UNIX is simple and coherent" - Dennis Ritchie; "GNU's Not Unix" - Richard Stallman

Offline

Board footer

Powered by FluxBB