对shell还不是很熟悉,平时遇到问题就要查资料,在这里开一个文档,记录一下以后遇到的常用的可复用的常用命令
1、覆盖和追加,常用在操作配置文件或者日志文件中
在文件后面追加内容 cat /template/hosts >> /etc/hosts 将文件内容覆盖 cat /template/hostname > /etc/hostname
2、获取某个进程的进程号或者杀掉某些进程
ps -ef |grep superset |grep -v grep |awk '{print $2}' 如果要杀掉这些进程,可以这么写,最后的sh是必须的,不然不会执行kill命令 ps -ef |grep superset |grep -v grep |awk '{print "kill -9 " $2}' |sh
3、判断某个进程运行是否正常,基本可以如下写,根据情况更换一下grep的条件
例如判断mysql运行是否正常 systemctl status mysql |grep "active (running)" >/dev/null if [ $? -eq 0 ];then echo "running" else echo "stopped" fi
4、安装数据库后执行一些初始化,主要展示EOF的用法
例如mysql安装后初始化数据以及设置用户名密码,并开放对外访问,可以类似这样 systemctl start mysql; mysql -uroot <<EOF source init-data.sql; USE mysql; UPDATE user SET authentication_string=password('xxxxx'),plugin='mysql_native_password' WHERE user=root'; GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'xxxxx' WITH GRANT OPTION; FLUSH PRIVILEGES; EOF 例如pg数据库,初始化设置用户密码以及创建新用户和创建数据库 systemctl start postgresql su - postgres << EOF psql -c " ALTER USER postgres WITH PASSWORD 'xxxx'" psql -c " create user pg-user with password 'xxxx';" psql -c " create database db-xxx with owner pg-user;" EOF
5、对于有交互式的输入,EOF就不太好用了,可以用expect(限于篇幅点到为止,不展开了),但是需要先安装yum包
yum -y install expect
以交互式的创建用户信息为例,创建create-user.sh文件,然后在需要交互式创建用户的脚本中调用这个sh文件即可,例如
bin/create-user.sh admin zhang yanhua zyh@admin.com xxxxx >> /opt/install.log
下面是是create-user.sh代码,很简单就是expect检测当前到了哪一步,对应send相应的内容
#!/usr/bin/expect set timeout 10 set username [lindex $argv 0] set firstname [lindex $argv 1] set lastname [lindex $argv 2] set email [lindex $argv 3] set password [lindex $argv 4] spawn fabmanager create-admin --app superset expect "Username" {send "$username "} expect "first" {send "$firstname "} expect "last" {send "$lastname "} expect "Email" {send "$email "} expect "Password" {send "$password "} expect "confirmation" {send "$password "} expect eof
再例如scp拷贝文件
#!/usr/bin/expect set timeout 10 set username [lindex $argv 0] set password [lindex $argv 1] set hostname [lindex $argv 2] spawn ssh-copy-id -i /root/.ssh/id_rsa.pub $username@$hostname expect { #first connect, no public key in ~/.ssh/known_hosts "Are you sure you want to continue connecting (yes/no)?" { send "yes " expect "password:" send "$password " } #already has public key in ~/.ssh/known_hosts "password:" { send "$password " } "Now try logging into the machine" { #it has authorized, do nothing! } } expect eof
6、让组件后台运行的一种方法,有时候组件的启动命令是前台运行的,占用控制台导致无法执行后续命令,如不是必须前台运行的话可以添加&让他后台运行,不影响继续执行后面的shell命令
前台运行,会一直占用控制台,不能再继续执行shell命令
superset runserver
后端运行,不占用控制台,可以继续执行其他shell命令
superset runserver&
7、常用的几个判断,文件、目录是否存在、文件是否包含某些内容
目录是否存在 if [ ! -d '/etc/monit.d' ]; then mkdir -p /etc/monit.d fi 文件是否存在 if [ ! -f "/etc/test.conf" ]; then touch /etc/test.conf fi 文件内是否包含某个字符串 if cat /opt/install.log |grep 'Admin User admin created';then echo 'create user success....' >> /opt/install.log else echo 'create user failed....' >> /opt/install.log fi