, , , ,

Difference between revisions of "Bash scripting"

From Camilo's web
Jump to: navigation, search
Mountain View
m
m
Line 13: Line 13:


== Examples ==
== Examples ==
===Reduce the size of multiple images===
#!/bin/bash
mkdir Reduced
echo 'Write the name of the files'
read filename
echo 'Write the reduction percentage'
read percentage
j=0
for i in <nowiki>$</nowiki>( ls -p | grep -v / )
do
  let "j=<nowiki>$</nowiki>j+1"
done
j=1
for i in <nowiki>$</nowiki>( ls)
do
  cp <nowiki>$</nowiki>i ./Reduced/<nowiki>$</nowiki>j.jpg
  let "j=<nowiki>$</nowiki>j+1"
done
cd Reduced
j=1
for i in <nowiki>$</nowiki>( ls)
do
  convert <nowiki>$</nowiki>i -resize <nowiki>$</nowiki>percentage% <nowiki>$</nowiki>filename<nowiki>$</nowiki>j.jpg
  let "j=<nowiki>$</nowiki>j+1"
done


===Alias to open a pdf file with TexShop ===
===Alias to open a pdf file with TexShop ===
The script is called ''ts'' and it contains the following lines:
The script is called ''ts'' and it contains the following lines:
  #!/bin/bash
  #!/bin/bash
  open -a TexShop "$1"
  open -a TexShop <nowiki>"$1"</nowiki>


Here the <nowiki>''$1''</nowiki> means that the script requires a parameter, which is this case is the file that you want to open.
Here the <nowiki>''$1''</nowiki> means that the script requires a parameter, which is this case is the file that you want to open.

Revision as of 16:45, 2 April 2018

How to create the script file

To create a bash script accessible globally throughout the terminal, you need to put it in a root folder accessible to the whole system. A good place to put it is

/usr/local/bin

There you can create (using your root role) the script file my_script, which should look like this:

#!/bin/bash
script line 1
script line 2
...

and once the coding is done, you need to make it executable

sudo chmod +x my_script

Examples

Reduce the size of multiple images

#!/bin/bash
mkdir Reduced

echo 'Write the name of the files'
read filename
echo 'Write the reduction percentage'
read percentage

j=0
for i in $( ls -p | grep -v / )
do
  let "j=$j+1"
done

j=1
for i in $( ls)
do
 cp $i ./Reduced/$j.jpg
 let "j=$j+1"
done

cd Reduced

j=1
for i in $( ls)
do
  convert $i -resize $percentage% $filename$j.jpg
  let "j=$j+1"
done


Alias to open a pdf file with TexShop

The script is called ts and it contains the following lines:

#!/bin/bash
open -a TexShop "$1"

Here the ''$1'' means that the script requires a parameter, which is this case is the file that you want to open.