






















| 标志 | 描述 |
|---|---|
$ echo $((013))
$ echo $((0xA4))还可以使用以下格式指定 2 到 64 之间的任意进制:
$((BASE#NUMBER))
使用 here document 提供 Shell 脚本使用信息
#!/bin/sh
cat << EOF
baseconv is a program to convert a number from one base to another.Usage: baseconv [options]
Options:
-i BASE input base
-o BASE output base
-h display this messageFor more information, consult the baseconv man page.
EOF
带前导缩进的 Shell 脚本 here document
#!/bin/shcat <<- EOF
baseconv is a program to convert a number from one base to another.Usage: baseconv [options]
Options:
-i BASE input base
-o BASE output base
-h display this messageFor more information, consult the baseconv man page.
EOF
$ bc << EOF
> ibase=16
> A
> EOF
10
$
可以在一个名为 subshell 的新 Shell 中执行一个或一组命令,当前 Shell 是 SubShell 的父 Shell。Subshell 继承父亲的环境。I/O 重定向可以出现在子 Shell 和父 Shell 之间,但是 Subshell 永远不能修改父环境。当您为了执行这些命令(比如设置变量)要更改 Shell 的环境,并且不想更改脚本自身运行所在的环境时,这就是您所期望的技术。当您想要同时在后台启动多个长时间运行的进程时也最好使用 Subshell。一个 Shell 可以生成多个 Subshell,而 Subshell 又可以循环生成属于它们自身的任意数量的 Subshell。
$ read VAR
23
$ echo $VAR
23
$
$ read -p "Instead of $VAR, what number would you like? " VAR
Instead of 23, what number would you like? 17
$ echo $VAR
17
$
$ ls | while read file; do ls $file; done
10
11
12
$
以下示例是执行有用功能的 Shell 单命令行程序样本。它们全部由本教程中描述的各种结构组成。
从当前目录中获取一组文件名恰好为两个字符长的文件,并使用 .ppm 扩展名为其重新命名:
for i in ??; { mv $i $i.ppm; }
使用 tar 和 Subshell 复制整个目录树,同时保持相同的文件权限:
( cd source ; tar pcf - * ) | ( cd target ; tar pxvf - )
读取二进制数并以十进制输出值:
read BINLOC;echo $((2#$BINLOC))
在 /usr/local 目录树中找到所有带 .mp3 扩展名的文件(这些文件的名称中可能包含空格字符),然后使用 bzip2 实用程序压缩这些文件:
find /usr/local -name "*.mp3" | while read name ; do bzip2 $name; done
将给定文件中所有十进制数的值以十六进制输出:
cat file | while read number ; do echo $((0x$number)); done
将给定文件中所有十进制数转换为十六进制的值,并将值输出到带有 .hex 扩展名的新文件中:
cat file | while read number ; do echo $((0x$number)) >> file.hex; done
构造重复十次的循环,以数字(从 0 到 90 以 10 递增)作为传递的参数运行 command:
i=0; while [ $i -ne 100 ]; do command $i; i=$(($i+10)); done
#!/bin/sh
# baseconv, convert numbers from one base to another.
#NUMBER=1
while [ $NUMBER ]; do
read -p "Input base: " IN
read -p "Output base: " OUT
read -p "Number: " NUMBER
bc -ql <<- EOF
obase=$OUT
ibase=$IN
$NUMBER
EOF
done
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。