问题
i whant to build a script to extract the word from a file in a command:
for example: in my file i keep my username , how can i export the username without knowing the username as part of my command , which my command is : suspend here should be the word exported?
From my file which has the text inside "JOHN" how can i tell the command : suspend that the username is JOHN ?
how can i cat/grep/sed the text from the file as part of command :
something like suspend |cat file , i have try that but the suspend command does not take the username , so there should be something different .
my ideea where like this
#!/bin/sh
username=cat my-file;
suspend $username ,
but i had no succes , because my $username is not display from the cat , the cat is shows it but thats all that is doing.
回答1:
Use the following syntax
username=$(cat my-file)
you might also use backquotes like
username=`cat my-file`
but the $(
...)
notation is preferable: it can be nested and is more readable.
Please read the Advanced Bash Scripting Guide (it will teach you a lot, even if it can be criticized)
Your usage of suspend
is incorrect, and I don't understand what you want to do with it. What would suspending a user mean to you? Perhaps you want to use pgrep or pkill
(to kill all the processes of that user, which I feel is too harsh)...?
回答2:
The command to read a line is, shockingly, named "read":
$ cat file
John
$ IFS= read -r username < file
$ echo "$username"
John
"cat" is the command to concatenate files.
Setting IFS=
and using the -r
arg to read are so that read handles leading white space and/or backslashes as-is rather then interpreting them. If you KNOW your file can never contain those or you want read to strip leading white space and/or interpret backslashes than you can get rid of those.
来源:https://stackoverflow.com/questions/17714810/use-text-and-use-as-command