加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

查看bash变量的确切内容? (hexdump没有帮助)

发布时间:2020-12-15 22:15:31 所属栏目:安全 来源:网络整理
导读:所以下面我有一个问题,但我的问题更通用 – 如何查看bash变量引用的内存的确切内容,以了解它们不匹配的原因: # [[ $c1 == $c ]] || echo nopenope# [[ $c1 == "bkup dt" ]] || echo nope# [[ $c == "bkup dt" ]] || echo nopenope# hexdump -C $c00000000 6
所以下面我有一个问题,但我的问题更通用 – 如何查看bash变量引用的内存的确切内容,以了解它们不匹配的原因:

# [[ $c1 == $c ]] || echo nope
nope
# [[ $c1 == "bkup dt" ]] || echo nope
# [[ $c == "bkup dt" ]] || echo nope
nope
# hexdump -C <<<$c
00000000  62 6b 75 70 20 64 74 0a                           |bkup dt.|
00000008
# hexdump -C <<<$c1
00000000  62 6b 75 70 20 64 74 0a                           |bkup dt.|
00000008
# [ "$c1" = "$c" ] || echo nope
nope
# [ ! "$c1" = "$c" ] || echo nope

或者它看起来像一个错误?我可以重复这个问题:

$cd /tmp
$mkdir aaa
$echo 2 > aaa/1
$echo 2 > aaa/2
$c=$(ls -A aaa)
$[[ $c == $(echo $c) ]] || echo not equal
not equal
$hexdump -C <<<$c
00000000  31 20 32 0a                                       |1 2.|
00000004
$hexdump -C <<<$(echo $c)
00000000  31 20 32 0a                                       |1 2.|
00000004
$c1="1 2"
$[[ $c1 == $(echo $c1) ]] || echo not equal
$[[ $c1 == $(echo $c) ]] || echo not equal
$[[ $c1 == $c ]] || echo not equal
not equal

解决方法

检查变量内容的最好方法是使用declare -p:

$c="1 2"
$declare -p c
declare -- c="1 2"

请注意,您的测试是错误的,因为您在变量扩展中遗漏了引号!

看:

$c="1  2" # with two spaces
$declare -p c
declare -- c="1  2"
$echo $c
1 2
$echo "$c"
1  2
$d=$(echo $c)
$declare -p d
1 2

您必须引用每个变量扩展,除非您真的想要应用单词拆分和路径名扩展! (通常,你当然不希望这种情况发生).

即使你的hexdump策略,你需要引用:

$c="1  2" # two spaces
$hexdump <<< $c
00000000  31 20 32 0a                                       |1 2.|
00000004
$hexdump <<< "$c"
00000000  31 20 20 32 0a                                    |1  2.|
00000005

你正在经历的是这样的:

$mkdir aaa; touch aaa/{1,2}
$c=$(ls -A aaa)
$declare -p c
declare -- c="1
2"
$# see? there's a new line between the files.
$echo $c
1 2
$echo "$c"
1
2
$# Use quotes!

有时,declare -p不会很好地显示空格.在这种情况下,您可以像这样使用printf:

$c=$'    n'
$declare -p c
declare -- c="    
"
$# there are spaces,but you can't see them
$printf '%qn' "$c"
$'    n'

声明策略也很好,因为您也可以检查数组和函数:

$a=( one two "three four" )
$declare -p a
declare -a a='([0]="one" [1]="two" [2]="three four")'
$declare -A h=( [one]=1 [two]=2 )
$declare -p h
declare -A h='([one]="1" [two]="2" )'
$f() { echo hello; } > somewhere > >(over the rainbow)
$declare -pf f
f () 
{ 
    echo hello
} > somewhere 2> >(over the rainbow)
$# You need also the -f switch to target functions

您还可以访问变量的标志:

$declare -litux hello=world
$declare -p hello
declare -itx hello="0"
$# Have fun!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读