内容:
(1) 环境变量;
(2) 字符串截取;
(3) if 关键字;
(1) 环境变量
定义一个环境变量:$ myvar='This is my environment variable!'
输出上面定义的环境变量:$ echo $myvar
This is my environment variable!
环境变量扩充:$ echo foo${myvar}bar
fooThis is my environment variable!bar
在程序中得到环境变量的值:
程序代码:myvar.c
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char *myenvvar=getenv("EDITOR");
printf("The editor environment variable is set to %s\n",myenvvar);
}
编译并运行程序:
$ gcc myenv.c -o myenv
$ EDITOR=xemacs
$ export EDITOR
$ ./myenv
The editor environment variable is set to xemacs
清空环境变量:$ unset EDITOR
$ ./myenv
The editor environment variable is set to (null)
(2)字符串截取
方式一:
$ basename /usr/local/share/doc/foo/foo.txt
foo.txt
$ basename /usr/home/drobbins
drobbins
方式二:
$ dirname /usr/local/share/doc/foo/foo.txt
/usr/local/share/doc/foo
$ dirname /usr/home/drobbins/
/usr/home
方式三:
$ MYVAR=foodforthought.jpg
$ echo ${MYVAR##*fo}
rthought.jpg
$ echo ${MYVAR#*fo}
odforthought.jpg
方式四:
$ MYFOO="chickensoup.tar.gz"
$ echo ${MYFOO%%.*}
chickensoup
$ echo ${MYFOO%.*}
chickensoup.tar
方式五:
$ EXCLAIM=cowabunga
$ echo ${EXCLAIM:0:3}
cow
$ echo ${EXCLAIM:3:7}
abunga
命令替换:
$ MYDIR=`dirname /usr/local/share/doc/foo/foo.txt`
$ echo $MYDIR
/usr/local/share/doc/foo
$ MYDIR=$(dirname /usr/local/share/doc/foo/foo.txt)
$ echo $MYDIR
/usr/local/share/doc/foo
字符串截取应用:
mytar.sh -- a sample script
#!/bin/bash
if [ "${1##*.}" = "tar" ]
then
echo This appears to be a tarball.
else
echo At first glance, this does not appear to be a tarball.
fi
chmod 755 mytar.sh
$ ./mytar.sh thisfile.tar
This appears to be a tarball.
$ ./mytar.sh thatfile.gz
At first glance, this does not appear to be a tarball.
(3) if 关键字
if [ condition ]
then
action
elif [ condition2 ]
then
action2
.
.
.
elif [ condition3 ]
then
else
actionx
fi
Bash学习笔记
最新推荐文章于 2024-08-05 19:39:45 发布