You are not logged in.
A script I just wrote to refresh pacman's mirrorlist when I see it's out of date.
#!/bin/bash
if [[ ${UID} -ne 0 ]] ; then
echo "You must be root to update pacman's mirrorlist."
exit 1
fi
(curl -s "https://www.archlinux.org/mirrorlist/?country=all&protocol=ftp&ip_version=4&use_mirror_status=on" | \
sed s/#Server/Server/g) > /etc/pacman.d/mirrorlist
pacman -Syy
Vanity of vanities, saith the Preacher, vanity of vanities; all is vanity.
What profit hath a man of all his labour which he taketh under the sun?
All the rivers run into the sea; yet the sea is not full; unto the place from whence the rivers come, thither they return again.
For in much wisdom is much grief: and he that increaseth knowledge increaseth sorrow.
Offline
Made this to manage my university website with Markdown.
#!/bin/bash
#
# Copies over files from a directory with markdown files
# (ending with .md) transformed into HTML files. The
# generated HTML files are prepended and appended
# respectively with .pre.html and .post.html from the
# source directory. TITLE in .pre.html is swapped with the
# first line in the markdown file.
#
# This script requires a markdown implementation such as
# discount.
#
# http://www.pell.portland.or.us/~orc/Code/discount/
#
function usage {
echo 'Usage: makeweb.sh <source-directory> <destination-directory>'
}
function gettitle {
title=$(head -n 1 $1 | sed 's/^\s*#*\s*//')
if ! [ -n "$title" ]; then
echo 'Untitled'
else
echo $title
fi
}
if ! [ -n "$1" -a -n "$2" ]; then
usage
exit 1
fi
if ! [ -d $1 -a -d $2 ]; then
usage
exit 1
fi
srcdir=$(cd $1 && pwd)
destdir=$(cd $2 && pwd)
if ! [ -f $srcdir/.pre.html ]; then
echo 'No .pre.html file in source directory!'
exit 1
fi
if ! [ -f $srcdir/.post.html ]; then
echo 'No .post.html file in source directory!'
exit 1
fi
echo "$srcdir -> $destdir"
cd $srcdir
for src in $(find -type f); do
if basename $src|egrep '.md$'; then
dest=$destdir/$(echo $src|sed 's/md$/html/')
cat $srcdir/.pre.html | sed "s/TITLE/$(gettitle $src)/" > $dest
markdown -f html $src >> $dest
cat $srcdir/.post.html >> $dest
elif basename $src|egrep -v '^\.'|egrep -v '~$'; then
cp $src $destdir/$i
fi
done
Last edited by Nichollan (2011-11-06 00:30:07)
Offline
Control a (possibly remote) slideshow in feh with signals.
#!/usr/bin/perl
kill('USR' . (pop =~ m/^n/ ? 1 : 2), qx(pgrep feh));
Offline
Create Qt Resource Files from the contents of a directory (e.g. Icons). One of my embarrassing attempts to write some Haskell
#! /usr/bin/runhaskell
module Main
where
import List
import System
import System.IO
import System.Directory
-- Returns a list of accepted resource types
type FileType = String
acceptedTypes :: [FileType]
acceptedTypes = ["png", "jpg"]
-- Extracts the file name from a path
getFileNameFromDirectory :: FilePath -> String
getFileNameFromDirectory f = reverse $ takeWhile (/= '/') rF
where rF = reverse f
-- Checks if the file is of one of the accepted types
isFileOk :: FilePath -> Bool
isFileOk [] = False
isFileOk f = suffix `elem` acceptedTypes
where suffix = reverse $ takeWhile (/= '.') (reverse f)
-- Main iteration function. Builds the xml string for each
-- file in a .qrc file
iterateFiles :: Handle -> String -> FilePath -> IO ()
iterateFiles _ [] _ = return ()
iterateFiles h p f = do
if isFileOk f
then do
-- Indentation tab
hPutStr h "\t"
-- A string of the form <file alias="example.png">../../example.png</file>
hPutStr h "<file "
hPutStr h "alias=\""
hPutStr h (getFileNameFromDirectory f)
hPutStr h "\">"
hPutStr h (p ++ f)
hPutStrLn h "</file>"
else do
putStrLn $ "Skipping " ++ f
-- Every .qrc file begins with this header
writeHeader :: Handle -> IO ()
writeHeader h = do
hPutStrLn h "<!DOCTYPE RCC><RCC version=\"1.0\">"
hPutStrLn h "<qresource>"
-- Close the tags at the end of the .qrc file
finishFile :: Handle -> IO ()
finishFile h = do
hPutStrLn h "</qresource>"
hPutStrLn h "</RCC>"
-- Entry point
-- -----------
main :: IO ()
main = do
args <- getArgs
if 2 == length args
then do
let directory = (args!!0)
exists <- doesDirectoryExist directory
if exists
then do
files <- getDirectoryContents directory
output <- openFile (args!!1) WriteMode
let iterFunc = iterateFiles output directory
writeHeader output
mapM_ (iterFunc) files
finishFile output
hClose output
else do
putStrLn $ "Directory " ++ directory ++ "does not exist. End."
else do
usage
usage :: IO ()
usage = putStrLn "Usage: dir2qrc [Icon directory] [qrc filename]"
Offline
This script toggles several screensaver/power-saving features.
Be sure to put something like
sed -i s/^SCREENSAVER.*/SCREENSAVER="on"/ $HOME/.screentoggle
in your startup script/.xinitrc.
#!/bin/bash
SCREENSAVER=on
case "$SCREENSAVER" in
on)
xset s off
xset -dpms
setterm -blank 0 -powerdown 0
sed -i s/^SCREENSAVER.*/SCREENSAVER="off"/ $0
# Example Notification: twmnc -t "Screensaver:" -c "off" -l twmn-screen.conf
;;
off)
xset s on
xset +dpms
setterm -blank 20 -powerdown 30
sed -i s/^SCREENSAVER.*/SCREENSAVER="on"/ $0
# Example Notification: twmnc -t "Screensaver:" -c "on"
;;
esac
Offline
mod action: merged in Doomcide's thread, original title "Simple Script To Toggle Screensaver".
aur S & M :: forum rules :: Community Ethos
Resources for Women, POC, LGBT*, and allies
Offline
mod action: merged in Doomcide's thread, original title "Simple Script To Toggle Screensaver".
Thanks, I wasn't sure if this deserved it's own thread and just went for it
Offline
I put that in my /etc/rc.local.shutdown to wake up my PC everyday at 7am :
# Automatic wakeup
D=`date --date=7 +%s` && [ $D -lt `date +%s` ] && D=`date --date='tomorrow 7' +%s`
echo 0 > /sys/class/rtc/rtc0/wakealarm && echo $D > /sys/class/rtc/rtc0/wakealarm
Offline
As a relative newcomer to Arch, I am discovering the great satisfaction gained from writing small bash scripts to automate a job that would normally take a bit more manual labour. I thought I'd start a thread here where people can share their own scripts that save those few precious seconds by automating the mundane.
Here's one I use quite frequently. Very simple, no magic. It checks if my Virtual machines are online, if so, prompts me to close them, kills them, then upgrades my packages and rebuilds VirtualBox's kernel modules. After that, it checks to see if pacman has made a new rc.conf and if so will open them up side by side for comparison before removing the .pacnew version.
#! /bin/bash
#************************************************
# Syu.sh
# Nov 14, 2011
#
# System upgrade and reconfiguration script.
#************************************************
function config ()
{
# Kill VirtualBox.
if ps ax | grep -v grep | grep VirtualBox > /dev/null
then
echo "Shut down all virtual machines then press Enter."
read
pkill VirtualBox
fi
pacman -Syu
# Rebuild vbox kernel modules.
sudo vboxbuild
sudo modprobe vboxdrv
}
function check_root ()
{
ROOT_UID=0
EXIT_NOTROOT=87
if [ "$UID" != "$ROOT_UID" ]
then
echo "Must be run as root."
exit $EXIT_NOTROOT
fi
}
function pacnew ()
{
echo "New rc.conf available. Edit [y/n]?"
read in
if [ "$in" == y -o "$in" == Y ]
then
pacnew_edit
fi
if [ "$in" == n -o "$in" == N ]
then
end
fi
pacnew
}
function pacnew_edit ()
{
meld /etc/rc.conf /etc/rc.conf.pacnew
echo "Remove rc.conf.pacnew?"
read in
if [ $in == y -o $in == Y ]
then
rm /etc/rc.conf.pacnew
echo "/etc/rc.conf.pacnew removed..."
fi
end
}
function end ()
{
echo "System update complete."
exit 0
}
check_root
config
echo ""
if [ -e /etc/rc.conf.pacnew ]
then
pacnew
fi
end
Regards
Ellis
"Paradoxically, learning stuff is information-society enemy number one"
Offline
Merged and cleaned up unnecessary posts.
Allan-Volunteer on the (topic being discussed) mailn lists. You never get the people who matters attention on the forums.
jasonwryan-Installing Arch is a measure of your literacy. Maintaining Arch is a measure of your diligence. Contributing to Arch is a measure of your competence.
Griemak-Bleeding edge, not bleeding flat. Edge denotes falls will occur from time to time. Bring your own parachute.
Offline
I made a little script that is a wrapper for Imagemagick, Tesseract, hocr2pdf, and Ghostscript.
Essentially, I convert a color-scanned image to black-and-white TIF (I found that OCR is better this way and it doesn't seem to slow the process down too much), apply OCR to that file, then combine the OCR data with the color image to be a color OCR PDF. It'll do this for all the JPGs in a directory, then combine the resulting PDFs into one multipage PDF and delete all the temporary working files.
It accepts a directory as an argument.
for file in $@*.jpg
do
echo 'Converting '${file}' to TIF format for OCR...'
convert ${file} -normalize -colorspace gray -colors 2 +dither -type bilevel ${file%*.jpg}.tif
echo 'Converting '${file%*.jpg}'.tif to hOCR format...'
tesseract ${file%*.jpg}.tif ${file%*.jpg} nobatch hocr
echo 'Combining hOCR with image data to produce output PDF...'
hocr2pdf -i ${file} -o ${file%*.jpg}.pdf < ${file%*.jpg}.html
done
echo 'Combining PDF documents...'
gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile=$@Combined-OCR.pdf $@*.pdf
echo 'Cleaning up '$@'...'
for file in $@*.jpg
do
rm ${file%*.jpg}.pdf &
rm ${file%*.jpg}.html &
rm ${file%*.jpg}.tif
done
This is my first bash script so some of the syntax and the like is probably sloppy.
Last edited by mrmylanman (2011-11-23 14:24:32)
Arch user since 2011-03-13
Thinkpad X220 Intel Core i7-2640M CPU, 16GB DDR3-1333 RAM, 160GB Intel SATA II SSD & 60GB OCZ mSATA SSD, 12.5" IPS 1366x768 Display, 6-cell Battery
(Installation date: 2012-03-19)
Offline
Been fooling around with a script to parse syslinux's config and easily load kernels via kexec:
#!/bin/bash
#
# kload - a syslinux.cfg parser for autoloading a kernel for kexec
#
bootloadercfg=/boot/syslinux/syslinux.cfg
error() {
local mesg=$1; shift
printf "==> ERROR: $mesg\n" "$@"
} >&2
die() {
error "$@"
exit 1
}
usage() {
cat <<EOF
usage: ${0##*/} <label> [rootoptions]
${0##*/} parses syslinux's bootloader configuration and automates the process
of loading a new kernel for kexec. If specified, any root options will override
the APPEND line of the config for a given kernel.
Options:
-f <file> use another config file (default: /boot/syslinux/syslinux.cfg)
-h display this help message.
-l display available kernels by label
EOF
exit 1
}
parse_config() {
awk -v action="$1" -v arg="$2" '
function longest(list, listlen,i, len, maxlen) {
maxlen = 0
listlen = length(list)
for(i in list) {
len = length(i)
if (len > maxlen) {
maxlen = len
}
}
return maxlen
}
function add_label(config, label, kernel, append, initrd) {
if (label && kernel && append) {
config[label] = kernel SUBSEP append SUBSEP initrd
}
}
function print_human(config, opts, len, label) {
if (length(config) == 0) {
print "==> ERROR: No kernel entries found in", FILENAME > "/dev/stderr"
return
}
len = longest(config)
printf "%-*s\t%s\n", len, "label", "kernel image [initrd]"
printf "%-*s\t%s\n", len, "", "options"
print "-------------------------------------------------------------"
for (label in config) {
if (config[label]) {
# opts[label] = <kernel> <append> [initrd]
split(config[label], opts, SUBSEP)
printf "%-*s\t%s", len, label, opts[1]
if(opts[3]) {
printf " [%s]", opts[3]
}
printf "\n%*s\t%s\n", len, "", opts[2]
}
}
}
function print_nullsep(config, label, opts) {
if (config[label]) {
split(config[label], opts, SUBSEP)
printf "%s\0%s\0%s\0", opts[1], opts[2], opts[3]
}
}
$1 == "LABEL" {
add_label(config, label, kernel, append, initrd)
label = $2
kernel = append = initrd = ""
}
label && $1 ~ /^(LINUX|KERNEL)$/ {
sub(/^[[:blank:]]*(LINUX|KERNEL) /, "")
kernel = $0
}
label && $1 == "APPEND" {
sub(/^[[:blank:]]*APPEND /, "")
gsub(/[[:blank:]]+/, " ")
append = append ? append " " $0 : $0
}
label && $1 == "INITRD" {
sub(/^[[:blank:]]*[^[:blank:]]+ /, "")
initrd = $0
}
END {
# if theres no line after the last section, we wont add the label
add_label(config, label, kernel, append, initrd)
if (action == "list") {
print_human(config)
} else if (action == "parse_one") {
print_nullsep(config, arg)
}
}
' "$bootloadercfg"
exit 0
}
runcmd() {
if (( needsroot )); then
if sudo -v &>/dev/null && sudo -l &>/dev/null; then
sudo "$@"
else
printf '%s ' 'root'
su -c "$(printf '%q ' "$@")"
fi
else
"$@"
fi
}
# main()
while getopts ":f:hl" flag; do
case $flag in
f) bootloadercfg=$OPTARG ;;
h) usage ;;
l) list=1 ;;
:) die "option '--%s' requires an argument" "$OPTARG" ;;
?) die "invalid option -- '%s'" "$OPTARG" ;;
esac
done
shift $(( OPTIND - 1 ))
[[ -f $bootloadercfg ]] || die "unable to find bootloader config: %s" "$bootloadercfg"
(( list )) && { parse_config 'list'; exit 0; }
label=$1; shift
[[ $label ]] || die "no label specified (use -h for help)"
(( UID == 0 )) || needsroot=1
{
read -rd '' kernel
read -rd '' append
read -rd '' initrd
} < <(parse_config 'parse_one' "$label")
[[ -z $kernel || -z $append ]] && die "failed to find label \`%s'" "$label"
kexec_cmd=(kexec -l "/boot/${kernel##*/}" --append="${*:-$append}")
[[ $initrd ]] && kexec_cmd+=(--initrd="/boot/${initrd##*/}")
printf 'executing: %s\n' "${kexec_cmd[*]}"
runcmd "${kexec_cmd[@]}"
Latest version can always be found on github.
Offline
Well fairly new to arch, used linux before however never really took to bash and then recently got back into it, due to arch's nature things are alot easier with a little bash. This is one of my first bash scripts.
Here is my script 'pacaur.sh' which installs a package if given the AUR tarball address. It uses a directory as a home in which it makes the package, so before use make the dir pacaur/
Usage: ./pacaur.sh http://aur.archlinux.org/packages/ar/ar … hey.tar.gz
*used archey for example*
#!/bin/bash
#variables
PACAUR_HOME=$HOME"/pacaur"
PACKAGE_URL=$1
init() {
cd $PACAUR_HOME
rm -rf *
}
getpackage() {
wget -q $PACKAGE_URL
}
makepackage() {
tar -zxf $(ls *.tar.gz | cut -d ' ' -f1 | head -n1)
cd $(ls -d */ | cut -d ' ' -f1 | head -n1)
makepkg -s
sudo pacman -U $(ls *.tar.xz | cut -d ' ' -f1 | head -n1)
}
init
getpackage
makepackage
comments/criticism and suggestions are welcome and appreciated
Last edited by warb0 (2011-11-26 13:39:53)
Offline
@warb0
Any reason why you don't figure out the download url for the user?
tar -zxf $(ls *.tar.gz | cut -d ' ' -f1 | head -n1)
Why? The directory has just one file, the one you downloaded, so ..??
sudo pacman -U $(ls *.tar.xz | cut -d ' ' -f1 | head -n1)
Why not e.g. 'sudo pacman -U *.tar.xz'? You can skip it altogether if you use 'makepkg -si'.
Using the output of 'ls' like this is bad practice. Read bash manual and some other resources https://wiki.archlinux.org/index.php/Le … sh.2FShell
Last edited by karol (2011-11-26 14:43:10)
Offline
@warb0
Any reason why you don't figure out the download url for the user?tar -zxf $(ls *.tar.gz | cut -d ' ' -f1 | head -n1)
Why? The directory has just one file, the one you downloaded, so ..??
sudo pacman -U $(ls *.tar.xz | cut -d ' ' -f1 | head -n1)
Why not e.g. 'sudo pacman -U *.tar.xz'? You can skip it altogether if you use 'makepkg -si'.
Using the output of 'ls' like this is bad practice. Read bash manual and some other resources https://wiki.archlinux.org/index.php/Le … sh.2FShell
Thanks for your input, as I said this is pretty much one of my first bash script other than basic things, I will take this into account, and probably submit a newer version at some point, however I see your point, some of my code here seems redundant. Also can you please explain how you would go about getting the url for the user? I'm assuming something along the lines of a wget/lynx --dump then cat/grepping the file for the url? Is there a better way for this?
warb0
Last edited by warb0 (2011-11-26 21:29:42)
Offline
Also can you please explain how you would go about getting the url for the user? I'm assuming something along the lines of a wget/lynx --dump then cat/grepping the file for the url? Is there a better way for this?
URLs follow a standard format. Assuming $1 is whatever you're passing into the script or function, it'd look like:
http://aur.archlinux.org/${1:0:2}/$1/$1.tar.gz
Technically, you shouldn't rely on this -- you should be using the RPC interface to the AUR which returns json (and looking at the URLPath element in the reply object).
Ignoring the RPC, you could write something naive such as:
#!/bin/bash
if curl -s "https://aur.archlinux.org/${1:0:2}/$1/$1.tar.gz" | bsdtar xz - 2>/dev/null; then
cd "$1" || { echo "error: failed to chdir to $1"; exit 1; }
else
echo "error: $1 not found"
exit 1
fi
makepkg -si
Last edited by falconindy (2011-11-26 22:23:33)
Offline
Very basic AUR Wrapper, update here: #1634
Last edited by Earnestly (2011-11-28 17:33:48)
Offline
What's wrong with yaourt?
Offline
Ah, I simply didn't want a fully-featured package manager for AUR, with little need, as most of the things I use come from official repos. I've added features to that script, but later removed them because it felt like unneeded bloat.
Nothing wrong with Yaourt, just personal preference.
Last edited by Earnestly (2011-11-27 13:19:59)
Offline
OK, makes sense. I was just curious really.
Offline
This is a little script I use to get a clearly arranged list of my mountpoints:
#!/bin/sh
# Copyright (C) 2011 by Raphael Scholer
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
# Set header
header="<filesystem> <dir> <type> <options> <label>"
# Get all mountpoints
mounts_all=$(mount -l | tr -d "()[]" |awk '{print $1,$3,$5,$6,$7}')
# Get only virtual mountpoints
mounts_virt=$(echo "${mounts_all}" |sed '/^\//d' |sort)
# Get only real mountpoints
mounts_real=$(echo "${mounts_all}" |sed '/^[[:alnum:]]/d' |sort)
if [[ ${1} == "--full" ]] || [[ ${1} == "-f" ]]; then
echo -e "${header}\n${mounts_virt}\n${mounts_real}" | column -t
else
echo -e "${header}\n${mounts_real}" |column -t
fi
Example output:
<filesystem> <dir> <type> <options> <label>
/dev/sda1 /boot ext2 rw boot
/dev/sda3 / ext4 rw,commit=0 root
/dev/sda5 /var ext4 rw,commit=0 var
/dev/sda6 /tmp ext4 rw,nosuid,nodev,commit=0 tmp
/dev/sda7 /home ext4 rw,commit=0 home
Offline
This is a little script I use to get a clearly arranged list of my mountpoints:
You should take a look at findmnt.
findmnt -o source,target,fstype,options,label -t ext2,ext4
Last edited by falconindy (2011-11-27 21:23:37)
Offline
You should take a look at findmnt.
Ah. Didn't know about it.
I am not able to get it to show any Labels. Besides the selection of real mountpoints is much easier in my script.
But still thanks for the information.
Offline
My synergy startup script.
#!/bin/bash
#
# Synergy Initialization Script.
#
SYN_SCREEN="picard"
SYN_XDISPLAY=":0.0"
SYN_HOST="wn7"
SYN_OPTS="--restart"
killall synergyc
synergyc ${SYN_OPTS} --display ${SYN_XDISPLAY} --name ${SYN_SCREEN} ${SYN_HOST}
Offline
Configures an external monitor connected over VGA.
#!/bin/bash
mode="$(xrandr -q|grep -A1 "VGA1 connected"| tail -1 |awk '{ print $1 }')"
if [ -n "$mode" ]; then
xrandr --output VGA1 --mode "$mode" --right-of LVDS1
xrandr --output LVDS1 --primary
else
xrandr --output VGA1 --off
fi
Offline