linux-如何在bash -c命令中插入變量


“ bash”命令啟動一個子進程,其父進程是您當前的bash會話.

要在父進程中定義變量並在子進程中使用它,必須將其導出.

先看一個簡單例子:
$FOO="text"
$echo $FOO
$text

$FOO="text"
$bash -c 'echo $FOO'
$# return nothing


$export FOO="text"
$bash -c 'echo $FOO'

要點:
1、 Subshells will have access to all variables from the parent, regardless of their exported state.
2、 Subprocesses will only see the exported variables.
What is common in these two constructs is that neither can pass variables back to the parent shell.
看下面的例子。
$ noexport=noexport; export export=export; (echo subshell: $noexport $export; subshell=subshell); bash -c 'echo subprocess: $noexport $export; subprocess=subprocess'; echo parent: $subshell $subprocess
subshell: noexport export
subprocess: export
parent:
$ noexport=noexport; export export=export; exec bash -c 'echo execd process: $noexport $export; execd=execd'; echo parent: $execd
execd process: export

上面解釋的很清楚了,再來看下面的一個例子和解釋:
如果我們創建一個普通變量和一個數組變量,
a=apple # a simple variable
arr=(apple) # an indexed array with a single element

and then echo the expression in the second column, we would get the result / behavior shown in the third column. The fourth column explains the behavior.

| Expression | Result(echo) | Comments

---+-------------+-------------+--------------------------------------------------------------------
1 | "$a" | apple | variables are expanded inside ""
2 | '$a' | $a | variables are not expanded inside ''
3 | "'$a'" | 'apple' | '' has no special meaning inside ""
4 | '"$a"' | "$a" | "" is treated literally inside ''
5 | ''' | invalid | can not escape a ' within ''; use "'" or $''' (ANSI-C quoting)
6 | "red$arocks"| red | $arocks does not expand $a; use ${a}rocks to preserve $a
7 | "redapple$" | redapple$ | $ followed by no variable name evaluates to $
8 | '"' | " | \ has no special meaning inside ''
9 | "'" | ' | ' is interpreted inside "" but has no significance for '
10 | """ | " | " is interpreted inside ""
11 | "*" | * | glob does not work inside "" or ''
12 | "\t\n" | \t\n | \t and \n have no special meaning inside "" or ''; use ANSI-C quoting
13 | "echo hi" | hi | and $() are evaluated inside "" 14 | '`echo hi`' | `echo hi` | and $() are not evaluated inside ''
15 | '${arr[0]}' | ${arr[0]} | array access not possible inside ''
16 | "${arr[0]}" | apple | array access works inside ""
17 | $'$a'' | $a' | single quotes can be escaped inside ANSI-C quoting
18 | "$'\t'" | $'\t' | ANSI-C quoting is not interpreted inside ""
19 | '!cmd' | !cmd | history expansion character '!' is ignored inside ''
20 | "!cmd" | cmd args | expands to the most recent command matching "cmd"
21 | $'!cmd' | !cmd | history expansion character '!' is ignored inside ANSI-C quotes
---+-------------+-------------+--------------------------------------------------------------------


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM