shell-01
questions and shell-01
为什么 for loop in {0..9}; 有分号,而 while 通常没有?
分号 ; 在 Shell 中主要作用是 “分隔命令”,让多个命令可以写在同一行。
结论:分号和循环类型(for/while)无关,只和 “是否把多个语法元素写在同一行” 有关。
{0..9}(两个点)和 {0...9}(三个点)的区别?
这是 Shell 中 “brace expansion(大括号扩展)” 的语法,用于生成序列,规则很明确:
{n..m}(两个点):
表示生成从 n 到 m 的连续整数序列(n 和 m 必须是整数,且 n <= m)。
echo {0..3} # 输出:0 1 2 3
echo {5..2} # 无效(n > m),输出:{5..2}
{n...m}(三个点):
在标准 Shell(如 Bash)中,三个点是无效语法,不会被解析为序列,会原样输出。
总结一下
分号 ;:用于同一行分隔多个命令 / 语法元素(如 for 条件和 do),多行写法可省略。
{n..m}:两个点,生成整数序列(主流 Shell 有效)。
{n...m}:三个点,无效语法,原样输出。
while(($int<=6))为什么两个括号?(自动识别,不用加$,这是冗余写法)
双括号 (( )) 是 Bash 为了简化数值计算和循环条件而设计的语法,让代码更像其他编程语言的风格,不用记 -le、-ge 这类特殊比较符,所以写起来更直观。记住:处理数字相关的循环 / 判断时,优先用 (( )) 就对了~
🌸(())只比较,不计算返回,$$(())计算并返回值
()组和$()命令提取符有什么区别
单括号 ():在 Shell 中主要用于 “命令组”(将多个命令组合成一个子进程执行),比如 (cd /tmp; ls),不用于数值计算。
1. ()
:子 shell / 命令分组
作用是在独立的子 shell 环境中执行括号内的命令,或单纯用于命令逻辑分组
2. $()
:命令替换
作用是执行括号内的命令,并捕获其输出内容,将输出作为字符串替换到当前位置
一句话总结
()
:“开个小窗口执行命令,结果不带到外面”;$()
:“执行命令,把它的输出结果抓出来用”。
()shell子进程,$()命令替换,执行命令并赋值
8-31-25
shell is a defense LANG shell是防御性的语言
#!/usr/bin/env bash
#8-31-25
#demo02.sh
#env bash will choose the suitable env to execute the shell
#export means copy fatherValue give childShell
export MY_NAME="ubutu"
bash -c 'echo "from child-shell: ${MY_NAME}"'
echo 'main shell '${MY_NAME}''
#loop-brance
#read command 对称之美 case-esac if-fi and so on
read -p "input y/n:" choice#-p prompt 读取然后赋值给变量
case "$choice" in
y|Y)#结束标志-固定写法
echo "this is yes:$choice"
;;#类似break
n|N)
echo "this is no:$choice"
;;
*)
echo "invalid input:$choice"
;;
esac
#if [];then;fi;
#if [];then;elif [];then;else;fi
if [ -x "./demo.sh" ]# -x -f -d等等只判断文件是否为可执行(x),文件(file),路径(directory)...
then
echo "this is a x file"
else
echo "not a x file"
fi
echo "$$ is pid of the file_name" # $$ 当前shell的pid
echo "$0 is the name of the file_name"
#the diffirent of [] and the [[]]
#[[]] only the bin/bash can use
#[ "$varName" = "example" ]
#!/usr/bin/env bash
#about the function
#$0 means the name of file
#$1-$9 and ${10-n} is the position of param
#$? means the returnValue last func returned.
#$$ is the pid of the running shell
# $(()) tell the interpret it's a func(can't fill with param)
add(){
echo "the sum is $(($1+$2)) with echo"
return $(($1+$2))
}
add 1 2
echo "the value is return with \$? $?"
#"$" and $,"" is more safe
#source and . can import other .sh like py or java
#for example
source demo02.sh
#. demo02.sh
’ “
- 单引号(' '):强引用
变量、转义字符(如$
、\
、*
)等都会被当作纯文本处理,不做任何解析。
示例:name="Alice"; echo 'Hello $name'
输出Hello $name
。- 双引号(" "):弱引用
会解析其中的变量($var) 和转义字符(如 $、"),其他字符按原样输出。
示例:name="Alice"; echo "Hello $name"
输出Hello Alice
。
$XX和”$XX"🔥
核心区别在于是否处理空格和特殊字符——"$xxx"
(双引号包裹)会保留变量值中的空格和特殊字符,而$xxx
(无引号)会把空格当作分隔符、解析通配符(如*
),实际行为可能完全不同