Я написал сценарий с именем xyzzy
, чтобы сделать это:
#!/bin/bash
i="$1"
i=$((${i//[^0-9]/}))
i="$(($i-1+0))"
b="$2"
b=$((${b//[^0-9]/}))
b="$(($b-1+0))"
if [ -z "$XYZZY_INDEX" ]; then
XYZZY_INDEX="$((-1))"
fi
if [ ! -f "/tmp/xyzzy.list" ]; then
touch /tmp/xyzzy.list
chmod a+rw /tmp/xyzzy.list
fi
readarray -t MYLIST < /tmp/xyzzy.list
showHelp(){
read -r -d '' MYHELP <<'EOB'
xyzzy 1.0
A command for manipulating escape routes from grues. Otherwise known as a useful system admin
tool for storing current directories and cycling through them rapidly. You'll wonder why this
wasn't created many moons ago.
Usage: xyzzy [options]
help/-h/--help Show the help.
this/-t/--this Store the current directory in /tmp/xyzzy.list
begone/-b/--begone Clear the /tmp/xyzzy.list file. However, succeed with a number and
it clears just that item from the stored list.
show/-s/--show Show the list of stored directories from /tmp/xyzzy.list
. # Use a number to 'cd' to that directory item in the stored list. This syntax is odd:
. xyzzy 2
...would change to the second directory in the list
. [no options] Use the command alone and it cd cycles through the next item in the stored
list, repeating to the top when it gets to the bottom. The dot and space before xyzzy
is required in order for the command to run in the current shell and not a subshell:
. xyzzy
Note that you can avoid the odd dot syntax by adding this to your ~/.bashrc file:
alias xyzzy=". xyzzy"
and then you can do "xyzzy" to cycle through directories, or "xyzzy {number}" to go to a
specific one.
May you never encounter another grue.
Copyright (c) 2016, Mike McKee
EOB
echo -e "$MYHELP\n"
}
storeThis(){
echo -e "With a stroke of your wand, you magically created the new escape route: $PWD"
echo "$PWD" >> /tmp/xyzzy.list
chmod a+rw /tmp/xyzzy.list
}
begoneList(){
if [[ "$b" == "-1" ]]; then
echo "POOF! Your escape routes are gone. We bless your soul from the ever-present grues!"
>/tmp/xyzzy.list
chmod a+rw /tmp/xyzzy.list
else
echo -n "Waving your wand in the dark, you successfully manage to remove one of your escape routes: "
echo "${MYLIST[${b}]}"
>/tmp/xyzzy.list
chmod a+rw /tmp/xyzzy.list
for x in "${MYLIST[@]}"; do
if [[ ! "$x" == "${MYLIST[${b}]}" ]]; then
echo "$x" >> /tmp/xyzzy.list
fi
done
fi
}
showList(){
echo -e "These are your escape routes:\n"
cat /tmp/xyzzy.list
}
cycleNext(){
MAXLINES=${#MYLIST[@]}
XYZZY_INDEX=$((XYZZY_INDEX+1))
if [[ $XYZZY_INDEX > $(($MAXLINES - 1)) ]]; then
XYZZY_INDEX=0
fi
MYLINE="${MYLIST[${XYZZY_INDEX}]}"
cd "$MYLINE";
}
switchDir(){
MYLINE="${MYLIST[${i}]}"
cd "$MYLINE";
}
if [[ "$@" == "" ]];
then
cycleNext
fi;
while [[ "$@" > 0 ]]; do case $1 in
help) showHelp;;
--help) showHelp;;
-h) showHelp;;
show) showList;;
-s) showList;;
--show) showList;;
list) showList;;
this) storeThis;;
--this) storeThis;;
-t) storeThis;;
begone) begoneList;;
--begone) begoneList;;
*) switchDir;;
esac; shift
done
export XYZZY_INDEX
Я использую его для копирования в папку / usr / bin
, а затем chmod a + x
на нем. Затем я редактирую файл моей учетной записи root и пользователя ~ / .bashrc
, чтобы включить эти строки внизу:
alias xyzzy='. xyzzy'
alias xy='. xyzzy'
«xy» - это сокращенная форма команды для более быстрого набора.
Затем я могу сохранить текущий каталог в списке с помощью ...
xyzzy this
... и при необходимости повторить. Как только я заполню этот список нужными мне каталогами, они останутся там до тех пор, пока я не перезагружу компьютер, потому что тогда / tmp снова будет очищен. Затем я могу ввести ...
xyzzy show
..., чтобы вывести список текущих сохраненных каталогов. Чтобы переключиться в каталог, у меня есть два варианта. Один из вариантов - указать путь по индексу (и это индекс, отсчитываемый от 1), например:
xyzzy 2
... который переключится на каталог, который является вторым элементом в списке. Или я мог бы оставить индексный номер и просто сделать:
xyzzy
... чтобы он перебирал каждый каталог по мере необходимости. Чтобы узнать о других командах, которые вы можете выполнить, введите:
xyzzy help
Конечно, работать веселее с глупыми операторами эха, которые я добавил.
Обратите внимание, что xyzzy - это отсылка к текстовому приключению Collosal Cave , где ввод xyzzy позволит вам переключаться между двумя комнатами в игре, чтобы избежать неприятностей.