The first little "trick" you should be aware of are the wildcard expansions (or globbing), here are some of the most used:
- * - Matches any string of characters
- ? - Matches any character
- [...] - Matches the defined characters
- [^...] - Negates the previous one (everything but what matches)
- {...} - Matches the specified strings
ls my_{file,doc}s
Which will list the files my_files and my_docs.
There is another thing you should know before starting to write bash scripts and that's the $(...) operation. What it does is represent the output of the program you invoke inside the brackets. Let's see it with an example:
Note:
- If the string contains spaces it must be delimited by quote marks;
- There can't be any spaces before or after the equal sign.
$read variable
abcde (Enter)
$echo $variable
abcde
At this time you're ready for your first program. In order to do that just open your favorite text editor and write the commands.
Comments in bash are represented by the character
#
, and continue to the end of the line. The only exception is the first line that should start with #!
and the path to the program used to run the file (usually /bin/bash). Also by convention the last line of the file should be exit 0
(for now just know that 0 represents successful in shell programming).The actual script could be something like this:
#!/bin/bash
echo "Name of file to cat:"
read file
cat $file
greeting="\nHello World"
echo -e $greeting
exit 0
This script waits for the name of a file, "cats" it and then writes Hello World to the output (not worrying with errors such as the file not existing).
The final step is to make the file executable, with
chmod
:$chmod +x file
and run it!
$./filename
No comments:
Post a Comment