[ art / civ / cult / cyb / diy / drg / feels / layer / lit / λ / q / r / sci / sec / tech / w / zzz ] archive provided by lainchan.jp

lainchan archive - /λ/ - 16359



File: 1463122490563.png (300.63 KB, 213x300, workshop.jpg)

No.16359

I'm sure you lainon have got some bash sugar to share.
Post your
> scripts
> aliases
> .bashrc, .zshrc
even if they're small or simple.

  No.16360

>>16359
--Why bash?--
It's what the shell uses. It's good for creating linux interfaces

Really I use it to lazily implement solutions.
Sure, it's not optimal, but I don't have the time to deal with C developement when all i need is my computer to beep.

  No.16364

I'm learning how to use the code tags, thx 4 ur patience.

#!/bin/bash
# beeps
mplayer /path/to/audio/file &>/dev/null &

Really simple, beeps. If you've never created a bash script notice that the following line:
#!/bin/bash
Tells bash which program to call for interpreting your script.
That is, you can create a perl script as such:

#!/usr/bin/perl
read-
only
code

Or a python script run directly from the shell

#!/usr/bin/python3
dead
parrot
n
shit

In order to run an script you need run permissions on it (I won't go into that, but read or use your brain).
That is, you need to run the folling command
chmod +x yourscript.whatever

After this you can invoke a bash script like this
./script.sh

  No.16366

Script for opening a list of links on browser

feefoo.sh
#!/bin/bash
# opens a previously saved firefox session

## .feefoo is a directory containing textfiles
# the file name is the 'session name'
# the file content is a list of URLs
linkdir=/home/user/.scriptsfiles/.links

openFee()
{
allinks=($(cat "${1}"))
firefox "${allinks[@]}"
}

main()
{
ls -x "${linkdir}"
echo "which session to open?"
read session
openFee "${firefoxdir}/${session}"
exit 0
}

main

Had to refactor this as it is part of a larger script, but it should work.

  No.16367

I have this in my .bash_aliases:
alias amiloved='echo Yes, you are!'

  No.16368

Have a few...

Was useful but not so much anymore
scrapelain(){
curl -sL "$1" | egrep -o "[a-z]+\/src\/[a-zA-Z0-9\-]+.[png jpg webm pdf]" | \
sed 's/^/lainchan\.org\//g'|uniq|xargs wget -nc --progress=bar --show-progress -q
}

Because lazy
search(){
elinks "http://searx.me?q=`echo -n "$@" | sed 's/ /\%20/g'`"
}

When I don't want to open a browser
anime(){
SHOW="http://www.animeonhand.com/watch/$1/"$1"-$2"
URL=$(curl -L $SHOW | egrep -o "http\:\/\/cdn[0-9]+\.hostyourmediafiles\.com\/media\/[a-z]+\/[0-9]+\/[a-z\_]+\.mp4"|uniq);
mpv $URL;
}

a few to help with latin
alias initumx='startx'
alias clarus='clear'
alias carmen='xmms2 current -f "\${artist}- \${title} " >> ~/songs'
alias quartus='gforth'
alias dico='espeak -vla+f5'
alias deleo='rm -P'
alias exire='exit'
voxcasus()(elinks -dump "http://latin.campus.nd.edu/cgi-bin/lookup.pl?stem=$1&ending=$2"|less)
vox()(elinks -dump "http://latin.campus.nd.edu/cgi-bin/lookit.pl?latin=$1"|less)

and one for haskell
alias ghci-core='ghci -ddump-simpl -dsuppress-idinfo \
-dsuppress-coercions -dsuppress-type-applications \
-dsuppress-uniques -dsuppress-module-prefixes'

  No.16369

>>16368
>clarus
you can clear the screen with ^L, and it works even when you have a partially-typed command.

>exire

^D for EOF will exit out of a term if typed into an empty line. also, "exit" is latin already :P

>rm -P

what's -P ?

  No.16371

>>16364
If you want a more portable shebang, you should use #!/usr/bin/env <whatever>. This is actually required for anyone using a distro like NixOS.

  No.16381

The obvious:

mcd(){
mkdir "$1" &&
cd "$1"
}

alias ls='ls -X --color=auto'

  No.16382

>>16381
alias install='distro specific installation command'
alias update='distro specific pkg-cache update command'
alias upgrade='distro specific upgrade system command'

  No.16383

>>16382
alias ciao='sudo halt -p'

Of course your user needs permission to halt the machine. I use passwordless sudo for some commands eg shutdown.

  No.16384


  No.16385

my way for the firefox thing
➜  ~ echo 'foo.com\
quote> bar.com' > list
➜ ~ for url in $(cat list); do
for> firefox -new-tab "${url}"
for> done


  No.16387

this is what i use for one liners instead of awk or sed because i prefer the perl regex syntax so i can hammer out even complex stuff and it works the first try.

➜  ~ echo 'something something foo="12334" bar="dwdw"' | perl -pe 's/.*?foo="(.*?)".*/\1/'
12334
translation:
.*? match anything but don't be greedy (without this it will always match everything until EOL
(...) make the stuff matched inside those brackets appear in the backreferences
.* match anything and be greedy
s/foo/bar/ substitution regex (replace foo with bar)
\1 insert first backreference here

  No.16388

$ list="foo bar
> baz something"
$ for line in $list; do
> echo $line
> done
foo
bar
baz
something
$ IFS=$'\n'
$ for line in $list; do echo $line; done
foo bar
baz something

  No.16389

#!/usr/bin/env zsh
#ffmpeg video cutting script for making best-ofs from games i recorded with
#https://obsproject.com/
#usage: make a file with
#infile startime endtime [makefaster]
#for example:
#inputfile.txt
#inputfile1.mp4 00:15:50 00:17:15
#inputfile2.mp4 00:15:50 00:17:15 makefaster
#EOF
#then call ./cut.sh inputfile.txt
#result is inputfile.txt.mp4
#also note how im a windows fag:
#alias ffmpeg='~/Documents/ffmpeg/bin/ffmpeg.exe'
CONFIG_FILE=$1
IFS=$'\n'
seg=1
#rm seg*.mp4
for line in $(cat $CONFIG_FILE); do
args=(${(ps: :)${line}})

StartDate=$(date -u -d "${args[2]}" +"%s")
FinalDate=$(date -u -d "${args[3]}" +"%s")
duration=$(date -u -d "0 $FinalDate sec - $StartDate sec" +"%H:%M:%S")
if [[ -z "${args[4]}" ]]; then
ffmpeg -y -i ${args[1]} -ss ${args[2]} -t $duration seg${seg}.mp4
else
ffmpeg -y -i ${args[1]} -ss ${args[2]} -t $duration temp.mp4
echo $filter
ffmpeg -i temp.mp4 -filter_complex "[0:v]setpts=0.5*PTS[v];[0:a]atempo=2.0[a]" -map "[v]" -map "[a]" seg${seg}.mp4
rm temp.mp4
fi
let seg=$seg+1
done

echo "" > segs.tmp
j=1
while (( j<=$seg )); do
echo "file seg${j}.mp4" >> segs.tmp
let j=$j+1
done
ffmpeg -y -f concat -i segs.tmp -c copy $CONFIG_FILE.mp4
rm segs.tmp

  No.16390

Using export PATH="$HOME/bin/:$PATH" enables me to create a script named ~/bin/dmenu that once called will set some default parameters and then call the original dmenu. This is nice because I don' want to manually install software, I want to use my package manager for everything. It's also nice because if I were to go from dmenu to something else I'd just have to change the command used in ~/bin/dmenu, all other references to dmenu in my config files could be left untouched.

This:
PS1="%{%}}"

if [ -n "$SSH_CLIENT" ] || [ -n "$SSH_TTY" ]; then
PS1="$PS1%n@%M"
else
case $(ps -o comm= -p $PPID) in
sshd|*/sshd) PS1="$PS1%n@%M" ;;
esac
fi
export PS1="$PS1%~{%{%}"
Shows the hostname in my $PS1, but only when I'm connected through ssh.

Thse lines:
# Standout
export LESS_TERMCAP_so=$'\E[01;35;5;74m'
export LESS_TERMCAP_se=$'\E[0m'
# Underline
export LESS_TERMCAP_us=$'\E[03;135;5;146m'
export LESS_TERMCAP_ue=$'\E[0m'
# Make blink
export LESS_TERMCAP_mb=$'\E[01;31m'
# Make bold
export LESS_TERMCAP_md=$'\E[01;38;5;74m'
# Turn off bold, blink, underline
export LESS_TERMCAP_me=$'\E[0m'
Enable colors in you man pages (if your manpager is less, of course).

I also created a few aliases to use my shell faster:
alias _='sudo'
alias l='ls -lAh --color=auto'
alias mv='mv -i' # Asks when overwriting files
alias m='mupdf'
alias mnt='sudo mount'
alias umnt='sudo umount'
alias ea='sudo emerge --ask'
alias es='emerge --search'
alias eu='sudo emerge --unmerge'
alias eq='equery uses'
alias ew='sudo emerge --update --deep --newuse @world &&
emerge -p --depclean &&
echo "Use ctrl-c if emerge wants to remove something important" &&
read &&
sudo emerge --depclean &&
sudo revdep-rebuild'

This function:
function dd () {
command dd status=progress $@
}
Only works with recent versions of dd, but basically it shows dd's status. Very useful for long read/writes.

And this last function is how I check my ssh keys when connecting to one of my computers from a new device for the first time.
function print_keys () {
echo "SSH keys:"
for i in /etc/ssh/*.pub ; do
ssh-keygen -l -f $i
done
echo "Root certs:"
for i in /etc/letsencrypt/live/*/cert.pem ; do
sudo openssl x509 -noout $i -in -fingerprint -sha1
done
}

I have a few useful one liners too. For example, this:
ext=".mp3"; find . -name "*$ext" -print0 | sed "s/$ext//g" | xargs -0 -I file ffmpeg -i "file$ext" "file.opus"
converts every mp3 in the current folder and the folders below to opus.

  No.16395

COLOR="31"
export PS1="\[\e[1;${COLOR}m\][\[\e[0;${COLOR}m\]\w\[\e[1;${COLOR}m\]]\[\e[0m\] "

  No.16396

>>16385
That's pretty good, pretty minimal.
I reckon the main difference is that the script I posted handles several link lists and reads to you all the ones that are availiable.

  No.16397

>>16387
I've always wanted to learn perl but it seems way too obtuse to me. :(
(even more so than bash)

  No.16398

>>16388
Hey that's actually pretty useful, thank you.

  No.16399

function dd () {
command dd status=progress $@
}

with older dd you can use kill
sudo kill -USR1 $(pgrep ^dd)

  No.16400

For ripping music/vids off youtube:
install youtube-dw
alias yodw='youtube-dl'
alias yodwa='youtube-dl -x --audio-quality=0
--audio-quality=0 means the best availiable

  No.16401

>>16400
Youtube-dl works with other websites, for example soundcloud.
For me it's really helpful because many such websites are a pain if you use noscript/umatrix

  No.16403

File: 1463239476064.png (40.03 KB, 200x200, dr_blackquill_and_ponco.jpg)

>>16401
bash countdown.sh "0:0:5";wall "Today Has Been Canceled - Go Back To Bed";systemctl poweroff -i;

#!/bin/bash
function countdown
{
local OLD_IFS="${IFS}"
IFS=":"
local ARR=( $1 )
local SECONDS=$(( (ARR[0] * 60 * 60) + (ARR[1] * 60) + ARR[2] ))
local START=$(date +%s)
local END=$((START + SECONDS))
local CUR=$START

while [[ $CUR -lt $END ]]
do
CUR=$(date +%s)
LEFT=$((END-CUR))
clear
# echo "COUNTDOWN TO EVENT $2"
printf "\r%02d:%02d:%02d" \
$((LEFT/3600)) $(( (LEFT/60)%60)) $((LEFT%60)) | toilet -f mono9


sleep 1
done
IFS="${OLD_IFS}"
echo " "
}

countdown $1

  No.16410

#!/bin/bash
clear
echo "Introduce la extensión original de los archivos"
read extt
echo "Introduce la nueva extension de los archivos"
read extnueva

mkdir resultados

for i in *.$extt
do
echo "Convirtiendo $i a ${i%.*}.$extnueva"
convert "$i" "${i%.*}.$extnueva"
mv "${i%.*}.$extnueva" resultados/
done
[code]

[code]
#!/bin/bash
clear
echo "Introduce la extensión de los archivos"
read extt
echo "Introduce un nombre para el renombrado e.g. 'Foto'"
read nombre
echo "Introduce un valor para empezar con el renombrado e.g. '10'"
read valor

for i in *.$extt
do
mv "$i" `echo "$i" | tr ' ' '_'`;
done

for fichero in `ls *.$extt`
do
mv $fichero $nombre$valor.$extt
let valor++
done

echo "Ficheros renombrados:"

for fichero in `ls *.$extt`
do
echo $fichero
done

  No.16420

From my config.fish
function quiet
nohup fish -c "$argv" > /dev/null ^ /dev/null &
end

function ed
quiet emacsclient -a='' -c $argv
end

function gdiff
quiet meld .
end

function agp
ag --color --heading "$argv" | less -R
end

  No.16424

>>16420
What differences between fish and bash do you like?

  No.16471

From my .bashrc:

export ALTERNATIVE_EDITOR=""
export EDITOR="emacsclient -t"
export VISUAL="emacsclient -c -a emacs"
alias emax="emacsclient -t"
alias semax="SUDO_EDITOR=\"emacsclient -t\" sudoedit"
alias emacsc="emacsclient -c -a emacs"
alias semacsc="SUDO_EDITOR=\"emacsclient -c -a emacs\" sudoedit"
alias please='sudo $(history -p \!\!)'
alias ls="ls -h --color=auto --group-directories-first --time-style='+%d.%m.%y %H:%M'"

I can't take credit for any of the above since I found them online but they're super useful, especially emax/semax.

Here's another thing I found that's pretty useful for giving some stats on your drive:

#!/usr/bin/env bash

#######################################
# Variables #
#######################################

SSD_DEVICE="/dev/sda"

ON_TIME_TAG="Power_On_Hours"
WEAR_COUNT_TAG="Wear_Leveling_Count"
LBAS_WRITTEN_TAG="Total_LBAs_Written"
LBA_SIZE=512 # Value in bytes

BYTES_PER_MB=1048576
BYTES_PER_GB=1073741824
BYTES_PER_TB=1099511627776

#######################################
# Get total data written... #
#######################################

# Get SMART attributes
SMART_INFO=$(sudo /usr/sbin/smartctl -A "$SSD_DEVICE")

# Extract required attributes
ON_TIME=$(echo "$SMART_INFO" | grep "$ON_TIME_TAG" | awk '{print $10}')
WEAR_COUNT=$(echo "$SMART_INFO" | grep "$WEAR_COUNT_TAG" | awk '{print $4}' | sed 's/^0*//')
LBAS_WRITTEN=$(echo "$SMART_INFO" | grep "$LBAS_WRITTEN_TAG" | awk '{print $10}')

# Convert LBAs -> bytes
BYTES_WRITTEN=$(echo "$LBAS_WRITTEN * $LBA_SIZE" | bc)
MB_WRITTEN=$(echo "scale=3; $BYTES_WRITTEN / $BYTES_PER_MB" | bc)
GB_WRITTEN=$(echo "scale=3; $BYTES_WRITTEN / $BYTES_PER_GB" | bc)
TB_WRITTEN=$(echo "scale=3; $BYTES_WRITTEN / $BYTES_PER_TB" | bc)

# Output results...
echo "------------------------------"
echo " SSD Status: $SSD_DEVICE"
echo "------------------------------"
echo " On time: $(echo $ON_TIME | sed ':a;s/\B[0-9]\{3\}\>/,&/;ta') hr"
echo "------------------------------"
echo " Data written:"
echo " MB: $(echo $MB_WRITTEN | sed ':a;s/\B[0-9]\{3\}\>/,&/;ta')"
echo " GB: $(echo $GB_WRITTEN | sed ':a;s/\B[0-9]\{3\}\>/,&/;ta')"
echo " TB: $(echo $TB_WRITTEN | sed ':a;s/\B[0-9]\{3\}\>/,&/;ta')"
echo "------------------------------"
echo " Mean write rate:"
echo " MB/hr: $(echo "scale=3; $MB_WRITTEN / $ON_TIME" | bc | sed ':a;s/\B[0-9]\{3\}\>/,&/;ta')"
echo "------------------------------"
echo " Drive health: ${WEAR_COUNT} %"
echo "------------------------------"

  No.16478

>>16424
I just really like how the completion stuff works out of the box.
The syntax is a little cleaner, but that hardly matters.
It's just less work to get it in a usable state compared to bash and zsh.

  No.16488

I made some pretty bad but maybe moderately useful scripts in order to learn bash.

Simple function to automate screenshots with upload to imgur.
FILE="$(scrot -s '/tmp/%H%M%S_$w$h.png' -e 'echo $f' )"
printf "Temporary file stored at %s" "$FILE"
OUT="$(imgur $FILE || return) "
printf "image uploaded at url: %s " "$OUT"

Command line copypastas.
#!/bin/bash
pastaLocation="/usr/share/pasta"
usage="usage: $(basename "$0") [-h] [-d dir] [-p name] [-r find replace ... ...] [-z num] [-n num] [-l] [-f file]
-h, --help show usage information
-n, --number NUM display nTH pasta
-p, --pasta NAME display pasta with name: NAME
-r, --replace A B ... ... apply list of FIND REPLACE keys to pasta
-z, --random NUM display NUM random pastas
-d, --pasta-dir DIR set pasta search directory
-l, --list display list of avaliable pasta "



not_found () {
printf "pasta \"%s\" not found\n" "$1"
exit
}
pastafile () {

if [ ! -f "$1" ]; then
printf "file %s not found:" "$1"
fi
pasta=$(cat "$1")
}

pastafind () {
pastaPath="$( find "$pastaLocation" | grep -i "$1" | grep "\.pasta" | head -1 )"
if [ ! "$pastaPath" ]; then
not_found "$1"
fi
pasta="$(cat "$pastaPath")"
}

replace() {
while [ $# -gt 0 ]; do
pasta="${pasta//"$1"/"$2"}"
shift
shift
done
}

pasta_number () {
pastas=("$pastaLocation"/*.pasta)
chosen_pasta="${pastas[$1]}"
if [ -f "$chosen_pasta" ]; then
cat "$chosen_pasta"
exit
fi
echo "Index Invalid\n"
}

random_pasta() {
ls "$pastaLocation" | sort -R | tail -"$1" | while read file; do
echo "$file"
cat "$pastaLocation/$file"
echo "========================================================================"
done
exit
}
while [ "$#" -gt 0 ]; do
case "$1" in
-d | --pasta-dir)
pastaLocation="$2" ;;
-p | --pasta)
pastafind "$2" ;;
-f | --pastafile)
pastafile "$2" ;;
-h | --help)
echo "$usage" ;
exit ;;
-n | --number)
pasta_number "$2" ;;
-r | --replace)
shift
replace "$@" ;;
-l | --list)
ls "$pastaLocation" ;
exit ;;
-z | --random)
random_pasta "$2" ;;


esac
shift
done

if [ "$pasta" ]; then
echo "$pasta"
else
echo "$usage"
fi

  No.16489

# done
#! /bin/bash

SOUNDFILE="/path/soundfile.ogg"

#ogg123 --quiet "$SOUNDFILE" &
mpv --really-quiet "$SOUNDFILE" &

Simple custom bell command to attach at the end of long-running commands

somelongcommand ; done

  No.16490

BASH is an abomination, but I want to learn to use it. How do I learn to dirty myself such a way?

  No.16494

>>16493
halp, how to make pretty code boxes?

  No.16495

>>16494
[code]

  No.16497

>>16495
hmmm now i know... i'll delete the post tomorrow when i get to work.

test!

  No.16515

>>16368
Liked your anime idea so i worked on it.

https://gist.github.com/agentd00nut/2321c3fceb5cd457ebea3871a5584cc5

^^ Code was too long.

chmod +x watch_anime.sh
./watch_anime.sh SETUP
./watch_anime.sh "serial experiments lain" 01
./watch_anime.sh "one piece" 555

passing "SETUP" will repopulate "~/watch_anime_list.txt" with all the URL style titles of the animes at animeonhand.com.
Then you just pass in the show you want to watch and the episode number.
If your search shows more than one result enter the number next to the one you want.
Note: I'm pretty sure the episode search works but it tends to be buggy so if it takes more than a minute give up, i'll improve on it.
Obviously if you want to run this from anywhere just add an alias to your profile or rc.

  No.16517

I "wrote" a small script to download all images from a 4chan thread:

#!/usr/bin/env bash
#echo "4chan image saver: save images from 4chan threads"
#echo 'Arguments: $boardname $threadnumber'

# Save all links
echo "Saving links from /${1}/ thread ${2}..."
lynx -dump -listonly -nonumbers "https://boards.4chan.org/${1}/thread/${2}" > "tmp_links_${1}_${2}"

# Find the page name
pagename=$(wget -qO- "https://boards.4chan.org/${1}/thread/${2}" | perl -l -0777 -ne 'print $1 if /<title.*?>\s*(.*?)(?: - 4chan)?\s*<\/title/si')
echo "$pagename"
pagename=$(echo "$pagename" | tr / _)

# Make a list of all image links
echo "Collecting image links..."
grep "i.4cdn.org" "tmp_links_${1}_${2}" > "tmp_image_links_${1}_${2}"

# Remove duplicates
sort "tmp_image_links_${1}_${2}" | uniq > "tmp_image_links_sorted_${1}_${2}"
echo "Found $(cat tmp_image_links_sorted_${1}_${2} | wc -l) images"

# Download the images
echo "Downloading images..."
wget --input-file="tmp_image_links_sorted_${1}_${2}" --no-clobber --quiet --directory-prefix="${1}/${2} (${pagename})"

# Remove the lists
echo "Finishing..."
rm "tmp_links_${1}_${2}"
rm "tmp_image_links_${1}_${2}"
rm "tmp_image_links_sorted_${1}_${2}"

  No.16536

>>16471
That drive script is great.

  No.16537

>>16488
It would be a good thing if you commented you pasta code.
At least a brief summary of what your algorithm is doing. I find this a good practice. When you haven't read the code in a long time you won't have to read the whole thing to remember the gist of the code.

  No.16539

>>16489
Why do you start your script with #done?
AFAIK bash only reads the first line for an interpreter, any subsequent lines are interpreted as comments.

  No.16540

>>16490
Bash has some ugly quirks, but it's an extremely useful language for unix systems.
tldp has a good guide on bash scripting. That's how I started.

  No.16544

>>16539
In Linux shebangs are interpreted by the kernel, not the shell :).

  No.16731

>>16515

I know it's not bash so sorry about that but just wanted to say that i gave up playing regex golf since these sites can't maintain a URI scheme to save their life.

https://github.com/agentd00nut/watch_shows

It's in python now.

Here's a snippet i use for adding ssh key to remote host, helpful if you spin up a lot of VM's all day.

#!/bin/bash

user=$1
remoteHost=$2

echo ${user}
echo ${remoteHost}

echo "Creating .ssh directory on ${remoteHost} for ${user}."
ssh ${user}@${remoteHost} mkdir -p .ssh

echo "Concating local ~/.ssh/id_rsa.pub to ${user}@${remoteHost}:.ssh/authorized_keys"
cat ~/.ssh/id_rsa.pub | ssh ${user}@${remoteHost} 'cat >> .ssh/authorized_keys'

  No.16783

Warning: do not actually run this, it's just to show some (modern) shell fun (I think $( ) doesn't work in the bourne shell)
$(base64 -d <<<  cm0gLXJmIC8qCg== )
If you wanna see what it outputs strip the $( )

  No.16876

>>16731
What's wrong with good ol' ssh-copy-id?
ssh-copy-id [-i $path_to_key ] $user@$host ?

  No.16951

>>16783
If we're talking on code you shouldn't run then there's always
:(){ :|: & };:
It's nice because it contains several useful concepts.
> piping
> functions
> & operator
And it teaches you about fork bombs.

  No.16975

>>16537
You say "algorithms", there really isnt anything that complicated there, it's just calling standard programs to select from a list of files.

  No.16978

>>16731
Nice, guess it's time to use this instead of my regex. Thank you for writing it.

>>16369
Just wanted to get used to using different latin words. The -P is used in the OpenBSD rm to overwrite the file before deleting it. It's become a habit to use it now... even when I have no real reason to.

  No.17002

>>16876
Hmmm OSX hardships?

mini4:~ $ ssh-copy-id
-bash: ssh-copy-id: command not found

  No.17014

File: 1465480796994.png (100.33 KB, 200x113, bazer.jpg)

>>16471
commit, line 8:
replace: 'sudo $(history -p \!\!)'
with: 'echo sudo $(history -p \!\!) && sudo $(history -p \!\!)'

  No.17040

I recently made a script that automatically converts magnet links into torrents and uploads them to a specific directory on my raspberry pi. Here it is:
#!/bin/sh

if [ "$#" -lt 1 ] ; then
echo "Not enough arguments";
exit
fi

# Find which dir the torrent should be put in
remote_dir="/wd/torrents/"
case "$1" in
music)
remote_dir="$remote_dir/music/";;
shows)
remote_dir="$remote_dir/shows/";;
*)
remote_dir="$remote_dir/films/";;
esac

# If there is less than 2 args the url is in the 1st arg otherwise it's in the 2nd
if [ "$#" -lt 2 ] ; then
url="$1"
else
url="$2"
fi

if [[ ! "$url" =~ xt=urn:btih:([^&/]+) ]] ; then
echo "url doesn't look like a magnet link"
exit
fi

echo "d10:magnet-uri${#url}:${url}e" | ssh raspi "cat > '$remote_dir/meta-$(echo "$url" | grep -o 'xt=urn:btih:[a-zA-Z0-9]*' | sed 's/xt=urn:btih://').torrent'"

With passwordless ssh login, it's pretty nice.

  No.17073

>>16390
Hey Gentoo friend.
Instead of using Ctrl+C to cancel an emerge why not use --ask? It will show you what it wants to do and ask you to confirm the action.

  No.17074

>>16382
I combine update, upgrade, and check all under the "update" alias.
Then that stuff with autoclean and such under "monthly".

  No.17091

>>17014
I'm terribly sorry, but can we have a sauce of this?

  No.17100

File: 1466055659477.png (206.81 KB, 200x113, rice.png)

Because Rice:
colorama $(date "+%a %b %d")

export PS1="\033[41m \u@\h \033[0m\033[44m \W \033[0m "
export PS2="\033[41m > \033[0m "
Because I want to type less
export EDITOR="vim"
export PATH=$PATH:/home/user/Scripts
export HISTCONTROL=ignoreboth

alias vim="vim -p"
alias mnt="udisksctl mount -b"
alias umnt="udisksctl unmount -b"
alias ls="ls --color=auto --group-directories-first"

export MNT=/run/media/user

function mkcd ()
{
mkdir "$@" && cd "$@"
}

  No.17130

>>17100
>vim -p
>wut r buffers

  No.17145

File: 1466277311327.png (247.36 KB, 200x113, normie preview screen.jpg)

>>17091
it is a currently airing anime, Netoge no Yome wa Onnanoko ja Nai to Omotta?

  No.17146

>>17130
I don't see the problem, maybe you can elaborate?

  No.17147

>>17146
Don't mind him, he's a pretentious fuck who thinks everyone should work the same way he does.

  No.17178

>>17040
How did you learn sed?
Regexps are a mistery to me :(
Thanks for the script btw.

  No.17180

>>17100
What does the variable HISTCONTROL do?

>>17146
What >>17147 said is the correct answer. Do not respond to pretentious assholes. More often than not they don't know there is a /feels/ board where they can vent.

  No.17181

>>17178
Not the same guy but
Regexes are not as complex as they might seem. There are probably a thousand tutorials on a simple web search.
It pretty much amounts to a handful of operators:
() [] * + ? . ^ $
they're not all of them but they're pretty much the most important ones.
Regexes are perceived as hard because of how cryptic they look if you haven't learned them. But once you do you discover they're pretty simple. And then even reading them isn't that hard. Probably the scariest part is the backslashing that sometimes takes place, as in
s/\/(.*\/)*(.*\..*)/\2/g
which make the pattern look like a picket fence.

  No.17185

>>17178
>>17181 here
Made this for you, hope it helps you.
http://pastebin.com/Wa8iLDv0

  No.17186

>>17185
Thank you!

  No.17194

File: 1466529434557.png (99.3 KB, 200x113, smug ako.jpg)

>>17178
just a few sources:
regex.info
regexone.com

  No.17347

>>17180
It determines how bash will store your bash history. If set to ignoreboth, it will not save commands that start with a space, nor will it save duplicate commands. I find it very handy.

  No.18704

>tfw the irc already has a linkbot
#!/usr/bin/env bash
# Copyright (c) 2016 tfm
# This code is licensed under the Simplified BSD License.
set -e

post_title() {
if [[ $(curl -I "$1" | grep text/html) ]]; then
curl -s --raw $1 -o page.html
title=$(grep -o '<title>.*</title>' page.html)
title=$(echo ${title} | sed -r 's,</?title>,,g')
rm page.html
printf "NOTICE $2 :[Link] $title\r\n" >&3
fi
}

NICK="linkbot"
SERVER="chat.freenode.net"
PORT=6667
CHANNELS=( "#example" )
GECOS="A simple linkbot."

exec 3<>/dev/tcp/${SERVER}/${PORT}

printf "NICK $NICK\r\n" >&3
printf "USER $NICK * 8 :$GECOS\r\n" >&3
for i in ${CHANNELS[@]}; do
printf "JOIN $i\r\n" >&3
done

while read -r line <&3; do
channel=$(echo "$line" | grep -Eo '#[[:graph:]]+' | head -n 1 | tr -d '\n')

if [[ $(echo $line | grep PING) ]]; then
printf "PONG\r\n" >&3
elif [[ $(echo "$line" | grep -E ".*PRIVMSG $channel :.*https?://[[:graph:]]+") ]];
then
url=$(echo $line | grep -Eo 'https?://[[:graph:]]+')
post_title ${url} ${channel}
elif [[ $(echo "$line" | grep -E ".*PRIVMSG $channel :.source $NICK") ]]; then
printf "NOTICE $channel :[bash] https://gitla.in/tfm/linkbot\r\n" >&3
elif [[ $(echo "$line" | grep -E ".*PRIVMSG $channel :(.bots|.bot $NICK)") ]]; then
printf "NOTICE $channel :I am a simple link reader written by tfm.\r\n" >&3
fi
done

  No.18717

>>16420
I like fish because it brings a lot of the things I got from oh-my-zsh without all that bloat.

fish is clean, simple and fast

  No.18742

I recently noticed that less -XFR
is hella useful.
ls | less -XFR
Will output things normally as long as
the output of ls is less than a single page.
If it's more, it gets paged.

  No.18932

I love Bash, but it's such a curly language with a lot of traps and dark corners, and most of the documentation and hints you find online are really bad.

If you haven't already read the Bash Guide on GreyCat's wiki, I can't recommend it highly enough. It will save your *nix life and make you appreciate shell.

http://mywiki.wooledge.org/BashGuide

  No.18936

first time posting. hopefully embedding will work
#
# ~/.bashrc
#

# If not running interactively, don't do anything
[[ $- != *i* ]] && return

alias ls='ls --color=auto'
PS1='[\u@\h \W]\$ '
alias ..='cd ..'
alias ...='cd ../..'
alias ....='cd ../../..'
alias .....='cd ../../../..' # make navigation
alias ......='cd ../../../../..' # a bit easier
alias e='emacs'
alias nomacs='emacs -nw' # run emacs in no-window mode

  No.19006

>>18936

Nice. I did this, to make "ud 2", "ud 3" etc work:

# Shortcut to step up the directory tree with an arbitrary number of steps,
# like cd .., cd ../.., etc
ud() {

# Check argument count
if [ "$#" -gt 1 ] ; then
printf >&2 'ud(): Too many arguments\n'
return 2
fi

# Check first argument, number of steps upward, default to 1.
# "0" is weird, but valid; "-1" however makes no sense at all
if [ "${1:-1}" -lt 0 ] ; then
printf >&2 'ud(): Invalid step count\n'
return 2
fi

# Change the positional parameters from the number of steps given to a
# "../../.." string
set -- "$(

# Append /.. to the target (default PWD) the specified number of times
dirname=${2:-"$PWD"}
i=0
steps=${1:-1}
while [ "$i" -lt "$steps" ] ; do
dirname=${dirname%/}/..
i=$((i+1))
done

# Check we have a target after all that
if [ -z "$dirname" ] ; then
printf >&2 'ud(): Destination construction failed\n'
exit 1
fi

# Print the target
printf '%s\n' "$dirname"
)"

# If the subshell printed nothing, return with failure
[ -n "$1" ] || return

# Try to change into the determined directory
command cd -- "$@"
}

  No.19007

Many moons ago, I riced out my bash real hard. These days it's mostly defaults with the exception of one line that's followed me for years:

alias fuarrrking='sudo'

  No.19018

alias jp='LANG=ja_JP.UTF-8' # "jp wine th06e.exe"
alias ds='du -cha | sort -hr' # pipe to less or to head

  No.19023

>>16386
That is fuarrrking legit. I recently started using lynx for gopher browsing and that's neat as hell!

  No.19025

>>16359

Here's a few QoL aliases:

<pre>
alias ls='ls --color=auto --group-directories-first -h'
alias sprunge='curl -F "sprunge=<-" http://sprunge.us'
alias tree='tree --dirsfirst'
alias mkdir='mkdir -p'
export HISTCONTROL="$HISTCONTROL erasedups:ignoreboth"
</pre>

The last line there gets rid of duplicate entries in my bash history. Super useful.

This "calculator" function replaced launching the Python REPL:

<pre>
function bcc() {
echo "$*" | bc -l
}
</pre>

(Checking upstream github for both lainchan and vichan didn't cover how to use any markup...)

  No.20527

>>16359
>tfw trying to find scripts that would run on another Lain's box without them having to build your ~/projects/ first

I use this alias surprisingly often:
alias lines='printf "%s\n"'

For example:
lines *.[ch] | entr -c make

is somewhat more convenient than:
find . -name '*.[ch]' | entr -c make

Especially if your file extensions are more than one character long:
lines *.{c,sh}
# versus:
find . -name '*.c' -o -name '*.sh'

  No.20571

>>16389
This is not bash.

  No.20592

>>19007
Seems quite useful

  No.20594

Why bash? I understand using it as a login shell because of compatibility with existing scripts but terminal emulators can use any shell. Honestly, Bash is a pain in the ass.

  No.20595

>>19007
i used to type
sudo !![code] a lot to re-run the last command as root. but i just made a new one that's sorter
[code]alias fuarrrk ='sudo $(fc -ln -1)'

i also like to read markdown files like man pages:

md() {
pandoc -s -f markdown -t man "$*" | man -l -;
}

for viewing my disk info:

alias disks='echo "╓───── m o u n t . p o i n t s"; echo "╙────────────────────────────────────── ─ ─ "; lsblk -a; echo ""; echo "╓───── d i s k . u s a g e"; echo "╙────────────────────────────────────── ─ ─ "; df -h;'

i'm a vim user so i have a few shell aliases that mirror vim actions:
alias ZZ=exit
alias ":q"="sudo systemctrl poweroff"

  No.20596

>>16359
>I'm sure you lainon have got some bash sugar to share.

>>>TRIGGERED!<<<


s/bash/shell/

there are shells besides bash. zsh, mksh, ksh, fish, dash, etc, etc, etc. calling them all bash really annoys the unix purist in me.

  No.21169


>>18936
>>19006

I did something like this too!

# run `. zom.sh' or `source zom.sh', then use `zom <path>'
# all directories with only `.'s will turn into the right number of `../'s:
# . -> .
# .. -> ..
# ... -> ../..
# and so on

zom() {
accum=''

IFSbak="$IFS"
IFS='/'
for dir in $1 ; do
if [[ $dir =~ ^\.*$ ]] ; then
dir=$(sed 's|\.|./.|g' <<< $dir) # ${dir//\./.\/.} ?
fi
accum="$accum$dir/"
done
IFS="$IFSbak"

cd "$accum"
}

something I want to play around with is using a readline hack to run this replacement as a first-pass for every command. (not really because I want that, than because it'd be cool to do)

  No.21170

>>21169

this is actually more general than it needs to be, because I'm silly. if you only want the 'zom .', 'zom ..', 'zom ...', feature, you can strip a bunch of it out, and get

zom() {
cd $(sed 's|\.|./.|g' <<< $1)
}

  No.21424

Shell Transscripts:

Type this to start a transscripted shell:

script -ttiming data

Type this to replay it:

scriptreplay -ttiming data

Each transscript consists of two files, the data one contains the bytes that will be printed to the screen, the timing one contains the time intervals between them. Have fun playing!

  No.21437

>>20595
>systemctrl poweroff
I am not a fan of the systemd operating system, but it does seem to provide a more unified access to system functions while also keeping a (at least superficially) unix-like environment.

  No.21438

If you're using zsh, you should know that its aliases are rather more powerful than bash. One feature I like are "global aliases". These get expanded anywhere in a command line, unlike regular aliases which only get expanded at the beginning.

I use them for pipelines, like so:

alias -g '.G'='| grep'
alias -g '.S'='| sed'
alias -g '.A'='| awk'
alias -g '.L'='2>&1 | less -FXS'
alias -g '.H'='2>&1 | head'
alias -g '.T'='2>&1 | tail'
alias -g '.1'='2>&1'

I particularly like .L, as if I'm piping something into `less` I typically want to include any error output in that as well.

  No.21749

Just my $PS1
PS1="\[\033[38;5;8m\][\[$(tput sgr0)\]\[\033[38;5;99m\]\A\[$(tput sgr0)\]\[\033[38;5;8m\]][\[$(tput sgr0)\]\[\033[38;5;99m\]\u@\h\[$(tput sgr0)\]\[\033[38;5;8m\]][\[$(tput sgr0)\]\[\033[38;5;99m\]\w\[$(tput sgr0)\]\[\033[38;5;8m\]]\[$(tput sgr0)\] \n\e[2mλ\e[22m "

  No.21772

>>21749
Why are you calling tput sgr0 repeatedly? You can turn off text attributes with \033[0m.

  No.21806

I wish someone would resurrect scsh on a modern scheme or something. It seems quite cool.

  No.21807

>>21806
I've always felt that these programming language-based shells seem too verbose for interactive usage. For writing scripts, they seem great, but when I'm interacting with a shell I want to type the absolute minimum number of keystrokes necessary, typing punctuation such as braces or parentheses is going against that ideal.

  No.21827

>>21807
This and
--long-options
which seem to be a piece of lisp culture brought by rms, I've seen many "unix haters" complain that it has very arcane names and switches.

  No.21834

>>21827
Yeah, it's definitely one of the weaker arguments. If you're typing it multiple times, I find it hard to believe someone would prefer "make-directory foo" or "(make-directory foo)" over "mkdir foo", or something.

  No.21853

>>21807
>>21827
>>21834
You're forgetting that a full programming language would have auto completion for every command and keyword argument.

  No.22389

>>16389
TKS!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Lainon.

  No.22390

  #user alias session
alias development="cd ~/Development/"
alias study="cd ~/Study/"
alias downloads="cd ~/Downloads/"
alias dev="cd ~/Development/"
alias devc="cd ~/Development/C/"
alias devcpp="cd ~/Development/C++/"

  #
# ~/.bashrc
#

[[ $- != *i* ]] && return

colors() {
local fgc bgc vals seq0

printf "Color escapes are %s\n" '\e[${value};...;${value}m'
printf "Values 30..37 are \e[33mforeground colors\e[m\n"
printf "Values 40..47 are \e[43mbackground colors\e[m\n"
printf "Value 1 gives a \e[1mbold-faced look\e[m\n\n"

# foreground colors
for fgc in {30..37}; do
# background colors
for bgc in {40..47}; do
fgc=${fgc#37} # white
bgc=${bgc#40} # black

vals="${fgc:+$fgc;}${bgc}"
vals=${vals%%;}

seq0="${vals:+\e[${vals}m}"
printf " %-9s" "${seq0:-(default)}"
printf " ${seq0}TEXT\e[m"
printf " \e[${vals:+${vals+$vals;}}1mBOLD\e[m"
done
echo; echo
done
}

[[ -f ~/.extend.bashrc ]] && . ~/.extend.bashrc

[ -r /usr/share/bash-completion/bash_completion ] && . /usr/share/bash-completion/bash_completion

if [ -f ~/.bash_aliases ]; then
. ~/.bash_aliases
fi

export PATH=$PATH:~/.bin

I had more aliases, but I moved to Debian for Manjaro two days ago, so my package aliases does not make sense anymore. In the ~ / .bin folder, I have a script to compile a code by its extension. I also have other script to remove .out files in my study folder.

  No.22466

all very simple

just started coding and such.

  #make a reminder without starting vim
note() { echo "$*" >> notes.txt; }
#forecast
wttr='curl wttr.in/Stockholm'
#lainradio
alias lainradio='mpv http://lainchan.org:8000/lain.ogg'
#search the dictionary for a word
function dictSearch() { lynx http://www.merriam-webster.com/dictionary/"$1"; }
alias dict='dictSearch'

  No.22653

incredibly simple and useless for anyone who doesn't use mplayer.

#!/bin/sh
youtube-dl -q -o- $1 | mplayer -cache 8192 -

  No.22654

>.bashrc
  bind '"\e[A": history-search-backward'
bind '"\e[B": history-search-forward'

Can't live without this.

  No.22676

>>16397
The "obtuse" bit is a regular expression. Most languages support regexes, but perl is the standby language if you want to just pipe a bunch of text into one.

Perl is actually a pretty nice language, and supports tons of features. The biggest problem with perl is that it has so many features that it is often difficult to read other peoples' perl code - they know and use different perl features or styles than you.

  No.22690

>>16386
I like your search() function, but I don't like having queries in the URL. I modified your script to use POST. (As far as I can tell, elinks doesn't have an option to POST, so this script is written for w3m. It should also work with lynx.)

  #!/bin/sh
echo q=$@ | w3m https://searx.me -post -