shell运行程序的过程
1、指令查找顺序
- 指定路径查找
- 如使用绝对路径或相对路径,如果路径下能找到对应程序,则执行
- alias查找
- 如果没找到执行命令,则继续往下找
- shell内置命令
- 不同的shell包含不同的内置命令,通常不需要shell到磁盘中去搜索
- help可以看内置命令
$ type echo
echo is a shell builtin
- PATH中查找
- 在PATH环境变量中查找,按路径找到的第一个程序会被执行
- 可以用whereis来确定位置
$ whereis ls
ls: /bin/ls /usr/share/man/man1/ls.1.g
2、如何让自己的程序像内置命令一样被识别(如./hello能直接用hello调用)
- 把自己的程序放到PATH的路径中,如/bin
$ hello
hello world
$ whereis hello
hello: /bin/hello
- 将当前路径加入到PATH
$ PATH=$PATH:./ #这种方式只在当前shell有效,所有shell生效可修改/etc/profile文件
$ hello
hello world
- 设置别名
$ alias hello="/temp/hello"
$ hello
hello world
- (补充)删除别名
unalias printf
自己写的简单脚本
1、将指定文件复制到指定目录下
#!/bin/bash
GIT_PATH="/home/lpc/gitee-graduate-project/graduate-project/clang-tidy-code"
CLANG_TOOLS_EXTRA_PROJECT="/home/lpc/llvm/llvm-project/clang-tools-extra"
CLANG_TIDY_CHECK_MISC="${CLANG_TOOLS_EXTRA_PROJECT}/clang-tidy/misc"
CLANG_TIDY_DOCS="${CLANG_TOOLS_EXTRA_PROJECT}/docs/clang-tidy/checks"
CLANG_TIDY_TEST="${CLANG_TOOLS_EXTRA_PROJECT}/test/clang-tidy/checkers"
CHECKERS=(LpcTestOneCheck)
DOCS_TESTS=(misc-lpc-test-one)
for cppName in ${CHECKERS}; do
cp ${CLANG_TIDY_CHECK_MISC}/${cppName}.cpp ${GIT_PATH}/check
cp ${CLANG_TIDY_CHECK_MISC}/${cppName}.h ${GIT_PATH}/check
done
for name in ${DOCS_TESTS}; do
cp ${CLANG_TIDY_DOCS}/${name}.rst ${GIT_PATH}/doc
cp ${CLANG_TIDY_TEST}/${name}.cpp ${GIT_PATH}/'test'
done
2、git提交
- 如果没有指定参数,则将时间作为默认commit信息
#!/bin/bash
git add .
echo $#
time=$(date "+%Y-%m-%d %H:%M:%S")
if [ $# == 0 ] ;then
echo ${time}
echo "no commit message, use time ${time} instead"
git commit -m "${time}"
else
echo "commit message is $1"
git commit -m "$1"
fi
git push
后台不挂断的运行
nohup:ssh断了也不会挂断执行,但会在终端输出
&:在后台运行
# 输出结果默认重写到当前目录下的nohup.out
nohup commands &
nohup python test.py > log.txt &
查看当前终端生效的后台进程
jobs -l
建立软链接到自己的可执行文件
sudo ln -s ~/tools/clash/clash-linux-amd64 /usr/bin/clash
sudo ln -s ~/clion/bin/clion.sh /usr/bin/clion
字符串操作
字符串包含
string='My long string'
if [[ $string == *"My long"* ]]; then
echo "It's there!"
fi
# 或者regex的版本
string='My string';
if [[ $string =~ "My" ]]; then
echo "It's there!"
fi
text=" <tag>bmnmn</tag> "
if [[ "$text" =~ "<tag>" ]]; then
echo "matched"
else
echo "not matched"
fi
文本读取
- 按行读取直到空
#!/usr/bin/bash
while read line
do
if [[ -z $line ]]
then
exit
fi
wget -x "http://someurl.com/${line}.pdf"
done < inputfile
# 其他不同场景的写法
while read line && [ "$line" != "quit" ]; do # ...
# stop at an empty line:
while read line && [ "$line" != "" ]; do # ...
while read line && [ -n "$line" ]; do # ...
- 一行行读取指定文本内容
cat file.txt | while read line; do
echo "$line"
done
cat peptides.txt | while read line || [[ -n $line ]];
do
# do something with $line here
done
#!/bin/bash
filename='peptides.txt'
echo Start
while read p; do
echo "$p"
done < "$filename"