Bash
分配給 bash 腳本中的變數
我有以下腳本,我嘗試創建一個空文本文件。我試過了
touch
,我試過echo -n >
了——他們都失敗了。#!/bin/bash set filename_result="contents" echo "filename=$filename_result" # Shows: filename= rm -f "$filename_result".json touch $filename_result # Error: usage: touch [-A [-][[hh]mm]SS] [-acfhm] [-r file] [-t [[CC]YY]MMDDhhmm[.SS]] file ... # Note that `% touch myfile` works fine on the command line touch -- "$filename_result" # Error: touch: : No such file or directory echo -n > "$filename_result" # Error: No such file or directory echo "[" >> "$filename_result" for file in *json do echo "examining file: $file" echo "\n" >> "$filename_result" cat $file >> "$filename_result" echo "\n" >> "$filename_result" done echo "\n]" >> "$filename_result" mv $filename_result "$filename_result".json
編輯:列印到螢幕
filename_result
變數顯示設置後它是空的?echo "filename=$filename_result" # Shows: filename=
試試這個:
filename_result=contents touch -- "$filename_result"
或者:
set contents touch -- "$1"
set filename_result="contents"
不給 賦值filename_result
。它分配給第一個位置參數,值本身是filename_result=contents
。例子:$ set filename_result="contents" $ echo "$1" filename_result=contents
變數
filename_result
不存在,$filename_result
擴展為空,"$filename_result"
等價於""
.而不是
set filename_result="contents"
你想要的只是filename_result="contents"