Skip to content

Posts from the ‘bash’ Category

Bash script to toggle samba on and off (and a button KDE)

Apr 13 10
by mat

I like using samba as a password-less method for people on a network to share and access files on my computer. This works well on a network you trust like a small home network or a small private network, however on different networks restricted access is preferred.

For me this problem is solved by simply having a button to turn samba on and off. This will also have the side effect that you will not be able to access anyone else’s shares but is sufficient for my needs.

Bash script

#!/bin/bash
smb=`sudo /etc/init.d/samba status | grep running | wc -l`
if [ $smb -gt 0 ]
then
	# Stop samba
	sudo /etc/init.d/samba stop
else
	# Start samba
	sudo /etc/init.d/samba restart
fi

Where username is replaced with your username.

The script simply checks the status of samba to see if it is running, if it is then it is killed otherwise it is started. kdialog is used to display a notification of which toggle state we are in.

Adding a notification (KDE)

#!/bin/bash
smb=`sudo /etc/init.d/samba status | grep running | wc -l`
if [ $smb -gt 0 ]
then
	# Stop samba
	sudo /etc/init.d/samba stop
	sudo -u username kdialog --passivepopup 'Samba off' 3
else
	# Start samba
	sudo /etc/init.d/samba restart
	sudo -u username kdialog --passivepopup 'Samba on' 3
fi

We run kdialog through `sudo -u username` because when the script is run with sudo the current user will be root, and using this will cause kdialog to display an ugly notification.

For an example of this try running `sudo kdialog “ugly message” 3`

kdialog run as root showing an ugly notification

kdialog run as root showing an ugly notification

As opposed to `sudo -u username kdialog –passivepopup ‘lovly message’ 3`

kdialog run as user showing an pretty notification

kdialog run as user showing an pretty notification

Creating an icon/button (KDE)
You can then turn this into a button you can simply click my creating a desktop file. In KDE Right click > new > link to application. Then fill in the application tab with the information as in the following image:

Samba toggle desktop button configuration

Samba toggle desktop button configuration

In the General tab you can give the button a name and choose the icon of your choice, click OK, and now you can drag your button to where ever you want it (taskbar, desktop, panel etc.) Then you can simple push the button to toggle samba on and off.

Utilising the notification system in KDE or Gnome in bash scripts (ubuntu 9.10 / linux)

Feb 18 10
by mat

So you want to use the nice notification features available in your desktop environment (KDE or Gnome) from a script you wrote? Below explains how to do just that for the two different environments.

KDE

The code below will use kdialog (should be installed along with kde) to create a popup message that displays for 3 seconds before closing:

kdialog --passivepopup 'notification message!' 3

This should look like the image below:

kdialog passive popup notification

kdialog passive popup notification

Source: stackoverflow

Gnome

A similar tool is available for gnome, but to the best of my knowledge (I don’t really use gnome) you need to install a package. The libnotify-

sudo apt-get install libnotify-bin

The command notify-send can then be used to create notifications from your script.

notify-send -t 3000 "notification title" "notification text"

Where 3000 is the timeout in milliseconds (so 3 seconds). notify-send features some nice additional options such as the ability to include images eg:

notify-send -i /home/user/exampleicon.png -t 3000 "notification title" "notification text"

Source: Coder’s Talk

Bash: Script to find active computers in a subnet using ping

Jan 27 10
by mat

The following is a simple bash script that will scan each ip address in a give subnet and report if they are alive (or accepting ping requests). The code creates processes for each ping so that it completes quickly rather than scanning each ip address sequentially.

Create a text file called “pinger.sh” and paste the following into it:

#!/bin/sh

: ${1?"Usage: $0 ip subnet to scan. eg '192.168.1.'"}

subnet=$1
for addr in `seq 0 1 255 `; do
#   ( echo $subnet$addr)
( ping -c 3 -t 5 $subnet$addr > /dev/null && echo $subnet$addr is Alive ) &
done 

Save and close, then it can be called from the command line like so:

sh pinger.sh 192.168.1.

This will scan from 192.168.1.0 to 192.168.1.255 and will return something like the following:

192.168.1.1 is Alive
192.168.1.105 is Alive
192.168.1.112 is Alive
192.168.1.149 is Alive

Bash: Script to convert .flv to mp3

Jan 18 10
by mat

Flash Video (.FLV) is currently a very popular format of online videos, inparticular youtube. This post explains how to use a simple script to extract the sound from a flash video file and turn it into an mp3.

In order for the script to work you will need to download ffmpeg (to decode the video) and lame (to encode the mp3). This can be achieve in ubuntu by opening a terminal and running the following or alternatively you can use your package manager GUI to search and download the packages for you.

sudo apt-get install ffmpeg lame

You then need to create a new file named “flv2mp3.sh” and paste the following into it using your preferred text editor (which hopefully isn’t VI). Save the file and then change the file permissions so that it is executable (by running:`chmod a+x flv2mp3.sh` in the terminal or via the gui in you file browser)

#!/bin/sh
# this script should convert files from FLV to WAV and then to MP3
echo " "
echo "  Welcome to FLV to MP3 converter!  version 0.1"
echo " "
infile_name="$@"
# exit if the user did not enter anything:
if [ -z "$infile_name" ]; then
    echo " "
    echo "You did not tell me the file name, so I will exit now."
    echo " "
    exit
fi
echo " "
ffmpeg -i "$infile_name" -acodec pcm_s16le -ac 2 -ab 128k -vn -y "${infile_name%.flv}.wav"
lame --preset cd "${infile_name%.flv}.wav" "${infile_name%.flv}.mp3"
rm "${infile_name%.flv}.wav"
echo " "
echo "OK. I'm done! Have fun!"
echo " "
exit 

You should now be able to convert a flashvideo into an mp3 by running the following command (changing the filenames to fit your purpose):
sh flv2mp3.sh videofilename.flv

Extra: Youtube
In linux it might be worth noting that youtube downloads the flv’s to your /tmp folder and you can easily copy them or convert to mp3′s (Ensure video is completly finished loading).

Also there is an application called ‘youtube-dl’ which can be installed from the repositories

sudo apt-get install youtube-dl

and then run using

youtube-dl http://www.youtube.com/video_to_borrow

Of course it’s up to your moral guidance to decide what you can and can’t download.

Partitions and disk space in linux

Sep 3 09
by mat

I’m sure there are many ways to see the partitions and corresponding diskspace in linux, but here is the method I found:

$df -m
Filesystem 1M-blocks Used Available Use% Mounted on
/dev/sda2 7513 5937 1576 80% /
tmpfs 1005 0 1005 0% /lib/init/rw
varrun 1005 1 1005 1% /var/run
varlock 1005 0 1005 0% /var/lock
udev 1005 1 1005 1% /dev
tmpfs 1005 1 1005 1% /dev/shm
/dev/sdc1 469453 353295 92311 80% /media/x
/dev/sdd1 1408345 979205 429141 70% /media/z

or visually:

df -m screenshot

I kept struggeling to remember what letters it was, as there are many two letter commands beginning with d in linux… (dc, dd, df, dh, do, dl, du). I now remember it, because ‘f’ is next to the ‘d’ key on my keyboard, and because df probably stands for disk-free.

For more information check out this site

Free

May 17 09
by mat

Using the free command gives output something like this (-m just tells free to output in megabytes):

free -m
total used free shared buffers cached
Mem: 2013 1996 17 0 27 1381
-/+ buffers/cache: 588 1425
Swap: 956 0 956

This is useful but annoying as it doesn’t show you how much memory is actually free. Files that are used are kept in the ram (referred to as caching). If the memory is needed it is simply overwritten, however if the file is used again it is already in the memory which saves time.

I wrote a quick little bash line to get the actually memory in use or the actual memory free. I use grep to select the right line from the output of free, and then use awk to do the string manipulation and math.

Memory in use

free -m | grep Mem | awk ‘{x=$3-$7; print x}’

Memory free

free -m | grep Mem | awk ‘{x=$2-($3-$7); print x}’

apt – no public key error

May 17 09
by mat

If you add a new repository to apt (/etc/apt/sources.list) you may get the following error when running ‘sudo apt-get update’:

Reading package lists… Done
W: There is no public key available for the following key IDs:
[Key]
W: You may want to run apt-get update to correct these problems

As you probably already guessed, running ‘sudo apt-get update’ will result in exactly the same problem. This is because the new repository’s key needs to verified. This is done by the following:

gpg –keyserver subkeys.pgp.net –recv [Key]
gpg –export [Key] | sudo apt-key add -

replace [Key] with the key you want to add

This can also be made slightly easier by using a bash variable:

$1=[key]
gpg –keyserver subkeys.pgp.net –recv $1
gpg –export $1 | sudo apt-key add -

replace [Key] with the key you want to add

or as a bash script:

#!/bin/sh
gpg –keyserver subkeys.pgp.net –recv $1
gpg –export $1 | sudo apt-key add -

ran by the following:

./key [key]

replace [Key] with the key you want to add
which then you could place in /bin so you could simply run

Script can be downloaded here

Bash: mass image and video conversions

May 16 09
by mat

Linux has many useful command line programs that will convert from one file format to another.

  • convert – converts images (part of ImageMagick)
  • convert input.jpg -resize 500×500 output.jpg

    converts input.jpg to output.jpg resized to 500 by 500 pixels

  • mencoder – converts video files
  • mencoder -ovc lavc -oac mp3lame -o output.avi input.flv

    converts input.flv to output.avi

    Now lets look at some bash:

    for i in *.jpg; do echo $i; done

    This is a for loop which will assign and iterate over a variable i to every item it finds that matches *.jpg in the current directory. It will simple echo the name of the file to the console and then finish. Only really useful for testing the command works, now lets put a conversion command in instead of the echo.

    for i in *.jpg; do convert “$i” -resize 500×500 “x_$i”; done

    This will take every jpg in the current directory resize it to 500 by 500 pixels and then save it as with and x_ prefixing the filename. You can get it to overwrite the current file by making the input and output file names equal (in this case it simple means removing x_ from the above code)