Reputation: 1767
I often write something like this:
cp -r folder-0.0.1 ~/temp
cp -r folder-0.2.2 ~/temp
cp -r folder-1.0.0 ~/temp
Template: <comand> <name>-<version> <path>
But instead, I'd like to write this:
do_something 0.0.1
do_something 0.2.2
do_something 1.0.0
Template: <alias> <version>
Can I do it easily in bash using aliases?
I would also like appropriate completion with tab key to work correctly. How can I program bash's completion to achieve this?
Upvotes: 4
Views: 826
Reputation: 46813
As Ignacio Vazquez-Abrams already mentioned, don't use aliases. In fact, it's even written in the Aliases section of the reference manual:
For almost every purpose, shell functions are preferred over aliases.
So you'll need that function:
do_something() {
[[ -n $1 ]] && cp -rnvt ~/test folder-"$1"
}
If you don't like the way I wrote the cp
with all its options, just remove them. For info:
-n
so as to not overwrite an existing file/folder-v
so as to be verbose-t
is the target directory(I like to write my cp
s like this, your version of cp
might not handle this, but very likely does).
There's also a check to make sure an argument was given before launching the cp
.
So far there's nothing better than the other answers. Regarding completion, here's what you can do:
_do_something() {
COMPREPLY=( $(
shopt -s nullglob extglob
files=( folder-+([[:digit:].])/ )
for ((i=0;i<${#files[@]};++i)); do
files[i]=${files[i]#folder-}
files[i]=${files[i]%/}
done
compgen -W "${files[*]}" -- "${COMP_WORDS[COMP_CWORD]}"
) )
return 0
}
complete -F _do_something do_something
Put this in your .bashrc
(even though it's probably not the best place for completions, you'll tweak all this when you're more experienced) and enjoy!
From here you'll want to extend this until it becomes a 100000 lines wonderful script. For example I added the -n
option in cp
(I believe it's a cool security feature). You could then want to add options to the do_something
function, for example an option --force
that will remove this -n
option. I won't do it for you (and it's beyond the scope of this answer), it's not that difficult, though. Then make sure you also alter the completion feature accordingly! It's a lot of fun.
Upvotes: 1