Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Linux Timesaving Techniques For Dummies.pdf
Скачиваний:
59
Добавлен:
15.03.2015
Размер:
15.98 Mб
Скачать

Using Aliases for Complex Commands

57

To save your aliases, use your favorite editor to add them to the ~/.bashrc file. This way, each time you log in, your aliases are there when you need them. To add system-wide aliases, check out Technique 8.

Using Aliases for Complex Commands

You can also create aliases that execute complex commands. For example, the following alias converts all GIF files in the current directory into PNG form:

alias cnv=’for fi in *.gif; do giftopnm $fi | pnmtopng > ${fi%%.gif}.png; done’

Aliases make it easy to create customized commands that are preconfigured with the arguments and options that you most frequently use. The find command is a great candidate for an alias or two because it’s such a complex command (see Technique 12). Here are two aliases that do the heavy lifting for you:

alias f=’find . -name’ alias fi=’find . -iname’

After defining these aliases, you can search for a file (by name) like this:

$ f myfile.sh

./tmp/myfile.sh

Or, use the second alias to search for a filename without regard to letter case:

$ fi myfile.sh

./tmp/myfile.sh

./work/MyFile.sh

Viewing your alias

When bash sees an alias name at the beginning of the command line, it replaces the alias name with the body of the alias. Normally, the substitution happens behind the scenes, and you can’t see it. If you want to see the substitution before you press the Enter key, just press Esc-E. For example, if you type fi myfile.sh and then press Esc-E, bash replaces your command line with find . -name myfile.sh.

Anything that could legally follow the alias body can follow the alias name. This means that you can include additional options on the command line when you use an alias. For example:

$ f myfile.sh -ls

819 8 -rw-rw-r-- 1 freddie freddie 5104 Feb 26 06:57./tmp/myfile.sh

bash aliases have one weakness: You can’t move command line arguments to other parts of the command. For example, consider this alias:

alias gf=”find . -type f -print0 | xargs -0 -e grep -n -e “

The gf alias combines find and grep to search for specific text in all the files in a directory tree. You can use the alias like this:

$ gf Martini

./recipes/drinks.txt:200: the perfect Martini

./spystories/bond.html:22: I prefer my Martinis shaken, not stirred

The gf alias works great as long as you want to search every file in a directory tree, but what if you want to search through .txt files and ignore .html files? You can’t do that with an alias because the -name qualifier has to go in the middle of the command line; it can’t be at the end. Instead, you need a function, which we explain how to create in the next section.

Соседние файлы в предмете Операционные системы