Saya memiliki operasi menggunakan cut
yang ingin saya berikan hasilnya ke variabel
var4=echo ztemp.xml |cut -f1 -d '.'
Saya mendapatkan kesalahan:
ztemp.xml bukan perintah
Nilai dari var4
tidak pernah ditugaskan; Saya mencoba untuk menetapkan output:
echo ztemp.xml | cut -f1 -d '.'
Bagaimana saya bisa melakukan itu?
Anda ingin memodifikasi tugas Anda untuk dibaca:
var4="$(echo ztemp.xml | cut -f1 -d '.')"
Konstruksi $(…)
dikenal sebagai command susbtitution .
Tergantung pada Shell yang Anda gunakan, Anda dapat menggunakan Ekspansi Parameter. Misalnya dalam bash
:
${parameter%Word}
${parameter%%Word}
Remove matching suffix pattern. The Word is expanded to produce
a pattern just as in pathname expansion. If the pattern matches
a trailing portion of the expanded value of parameter, then the
result of the expansion is the expanded value of parameter with
the shortest matching pattern (the ``%'' case) or the longest
matching pattern (the ``%%'' case) deleted. If parameter is @
or *, the pattern removal operation is applied to each posi‐
tional parameter in turn, and the expansion is the resultant
list. If parameter is an array variable subscripted with @ or
*, the pattern removal operation is applied to each member of
the array in turn, and the expansion is the resultant list.
Dalam kasus Anda itu berarti melakukan sesuatu seperti ini:
var4=ztemp.xml
var4=${var4%.*}
Perhatikan bahwa karakter #
berperilaku serupa di bagian awalan string.
Ksh, Zsh, dan Bash semuanya menawarkan sintaks lain yang mungkin lebih jelas:
var4=$(echo ztemp.xml | cut -f1 -d '.')
Backticks (a.k.a. "Aksen kubur") tidak dapat dibaca dalam beberapa font. Sintaks $(blahblah)
jauh lebih jelas.
Perhatikan bahwa Anda dapat mem-pipe nilai ke perintah read
di beberapa shell:
ls -1 \*.\* | cut -f1 -d'.' | while read VAR4; do echo $VAR4; done
Ini adalah cara lain untuk menetapkan variabel, baik digunakan dengan beberapa editor teks yang tidak dapat menyorot dengan benar setiap kode rumit yang Anda buat.
read -r -d '' str < <(cat somefile.txt)
echo "${#str}"
echo "$str"