我想编写一个bash脚本来自动将用户添加到vncserver
配置文件中。根据Centos guide,我必须编辑/etc/sysconfig/vncserver
和
VNCSERVERS="1:user1"
扩展为VNCSERVERS="1:user1 2:user2"
VNCSERVERARGS[2]="-geometry 1250x700"
因此,通过运行./add_user_to_vnc user2
,原始文件的内容将从
VNCSERVERS="1:user1"
VNCSERVERARGS[1]="-geometry 1250x700"
到
VNCSERVERS="1:user1 2:user2"
VNCSERVERARGS[1]="-geometry 1250x700"
VNCSERVERARGS[2]="-geometry 1250x700"
这样一个脚本的两个难点(对我来说)是维护一个计数器并展开第一行。使用echo >>
命令添加最后一行应该相当简单!
有什么想法吗?
答案 0 :(得分:2)
我将如何做到这一点:
#!/bin/bash
# Get new user name
new_user="$1"
# Get list of current users
servers="$(grep 'VNCSERVERS' vncserver)"
# Extract counter of last user
users="${servers#*\"}" # Remove everything up to first quote
last_user="${users##* }" # Remove everything up to last space
ctr="${last_user%%:*}" # Remove everything starting from colon
# Increase counter
(( ++ctr ))
# Remove trailing quotes from line with current users
servers="${servers%\"}"
# Construct new first line
printf -v servers "%s %d:%s\"" "$servers" "$ctr" "$new_user"
# Construct new line for server args
serv_args="VNCSERVERARGS[$ctr]=\"-geometry 1250x700\""
# Use sed to replace first line and append last line
sed '1s/.*/'"$servers"'/;$a\'"$serv_args"'' vncserver
说明:
vncserver
文件,您必须这样做
./script > vncserver
在处理文件之前会截断文件,并且您最终会得到一个空文件)sed -i
(或BSD sed:sed -i''
)进行就地处理。要保留备份文件,请使用sed -i.bak
。有些seds需要在追加命令a\
之后换行; sed命令将变为
sed '1s/.*/'"$servers"'/;$a\
'"$serv_args"'' vncserver
示例用法(使用sed -i
):
$ cat vncserver
VNCSERVERS="1:user1"
VNCSERVERARGS[1]="-geometry 1250x700"
$ ./SO.sh user2
$ cat vncserver
VNCSERVERS="1:user1 2:user2"
VNCSERVERARGS[1]="-geometry 1250x700"
VNCSERVERARGS[2]="-geometry 1250x700"
$ ./SO.sh another_user
$ cat vncserver
VNCSERVERS="1:user1 2:user2 3:another_user"
VNCSERVERARGS[1]="-geometry 1250x700"
VNCSERVERARGS[2]="-geometry 1250x700"
VNCSERVERARGS[3]="-geometry 1250x700"
$ ./SO.sh latest_user
$ cat vncserver
VNCSERVERS="1:user1 2:user2 3:another_user 4:latest_user"
VNCSERVERARGS[1]="-geometry 1250x700"
VNCSERVERARGS[2]="-geometry 1250x700"
VNCSERVERARGS[3]="-geometry 1250x700"
VNCSERVERARGS[4]="-geometry 1250x700"