Archive

bash

Using bash and ImageMagick we can crop all the pictures in a folder in a single shoot:

fix='crop'
it=1
for file in $2/*; 
do
    if [[ -f $file ]]; 
    then
        output=$2/${fix}${it}.png
        echo "$file --> $output"
        convert -crop $1 "$file" "$output"
        it=$((it+1))
    fi
done

The script, called crop.sh is run as:

./crop.sh 525x240+675+150 ~/Pictures/

The first argument is the argument for the ImageMagick’s crop tool and the second argumen is the folder where the pictures to be cropped are.

Currently I’m writing a pipeline, better call it a pipeline manager, in BASH. The first part of the script is to create the set up file system so it requests to check if certain files and folders exists.

Hence the idea is to use the BASH tests, that can be performed both using the keyword test and [. The syntax is:

[ parameter FILE ]

or

test parameter FILE

Where parameter can be any one of the following:

  • -e: Returns true value if file exists
  • -f: Return true value if file exists and regular file
  • -r: Return true value if file exists and is readable
  • -w: Return true value if file exists and is writable
  • -x: Return true value if file exists and is executable
  • -d: Return true value if exists and is a directory
  • -L: Return true value if exists and is a link

An example to test if a file exists in a script file could be:

#!/bin/bash
FILE=$1

if [ -f $FILE ]; then
   echo "File $FILE exists"
else
   echo "File $FILE does not exists"
fi

The same used as an in-line command:

$ [ -f ~/blog/bash_test.md ] && echo "File exists" || echo "File does not exists"

I used to create (GNU/Linux) alias as way to rename the standard commands, like this:

alias rm='rm -rf'

But since I started the PhD, each time I use more sophisticated commands and today I want to create an alias that accepts arguments. Let see, I want a command to obtain the result of running:

ls -a | nl

Thit was perfect to see the numbered files in the actual path.

alias lsn='ls -a | nl'

But when doing that:

lsn /tmp/

I got an unexpected error:

nl: /tmp: Is a directory

And that because the argument /tmp is given to the second particle of the pipe, to the nl and not to the ls -a. It is know that alias doses not accept arguments (correct me if I’m wrong). So the solution to that is to use bash function and assign the function to the alias.

First we can create the function that accepts the argument and runs the desired command:

lsn_fun() {
ls -a $1 | nl
}

And we assign the function to the alias:

alias lsn=lsn_fun

So now we can run the alias using arguments:

lsn /tmp

1 .
2 ..
3 12904-rsession
4 13126-rsession