[英]Global bash script alias created from bash script
I am making some service and I have a setup.sh file which must be exectued first time (or on update). 我正在提供一些服务,并且我有一个setup.sh文件,该文件必须在第一次(或更新时)执行。 This script should create some kind of alias which will be accessible from this or new terminal (also after system restart).
该脚本应创建某种别名,可以从此终端或新终端访问(也可以在系统重启后)。 This alias should point to another executable sh file.
该别名应指向另一个可执行的sh文件。
The setup.sh file: setup.sh文件:
#!/bin/bash
alias customservice='./customservice.sh "$@"'
As you can see this customservice.sh script is ready to accept multiple arguments. 如您所见,此customservice.sh脚本已准备就绪,可以接受多个参数。 With this customservice alias I want to call this script like this:
使用此customservice别名,我想这样调用此脚本:
customservice //show help
customservice //显示帮助
customservice startcustomservice启动
customservice stop定制服务站
customservice exec bashcustomservice exec bash
......
My customservice.sh fil: 我的customservice.sh fil:
if [ $# -eq 1 ] && [ $1 = "start" ]; then
//do something
elif [ $# -eq 1 ] && [ $1 = "stop" ]; then
//do something
elif [ $# > 1 ] && [ $1 = "exec" ]; then
//do stuff with ${@:2}
else
echo "help"
fi
Maybe customscript kill command would be nice too. 也许customscript kill命令也很好。 It should remove this alias entirely.
它应该完全删除该别名。
Maybe, if this approach is deprecated, I am open for better solutions. 也许,如果不赞成使用这种方法,我愿意寻求更好的解决方案。
That's not the best way to do what you are aiming for. 这不是实现目标的最佳方法。 If you can reconsider your approach I would suggest doing the following:
如果您可以重新考虑您的方法,我建议您执行以下操作:
~/.bashrc
( or similar ) to set the path to script: export PATH=$PATH:/path/to/script/dir
~/.bashrc
(或类似文件)来设置脚本的路径: export PATH=$PATH:/path/to/script/dir
customservice
, not customservice.sh
. customservice
,而不是customservice.sh
。 #!/usr/bin/sh
or #!/bin/bash
depending on what you need to execute it and the location of interpreter. #!/usr/bin/sh
或#!/bin/bash
这取决于您需要执行什么以及解释器的位置。 Alternatively, for universal approach you can use #!/usr/bin/env bash
. #!/usr/bin/env bash
。 Benefits: 优点:
$@
to an alias, which can be dirty. $@
传递给别名的方法,该别名可能很脏。 If you don't want to use the direct approach, Make a Bash alias that takes a parameter? 如果您不想使用直接方法,是否可以使用带有参数的Bash别名? should fully address your needs.
应该充分满足您的需求。
If you are looking to load aliases in ~/.bashrc: 如果要在〜/ .bashrc中加载别名:
#!/bin/bash
#add following in your setup.sh
cat << EOF >> ~/.bashrc
alias customservice='./customservice.sh \"\$@\"'
EOF
on new terminals having bash shell as default it should activate the alias. 在默认使用bash shell的新终端上,应激活别名。
obviously, you should grep in your ~/.bashrc with your setup.sh before installing the lines in case the alias is already present. 显然,在安装这些行之前,应该使用您的setup.sh在〜/ .bashrc中使用grep,以防别名已经存在。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.