如何在 shell 脚本中导入和使用 config/param 文件中的变量
How to import and use variables from a config/param file in a shell script
我的 /home/s/project/bin/FileOperation.sh
文件是:
#!/bin/ksh
/home/s/project/Param/Param_File.config
current=$(dirname [=12=])
echo $current
echo 'hello'
echo $RootDir
echo $message
我的 /home/s/project/Param/Param_File.config
文件是:
RootDir=/home/s/project
message=hello
当我执行上面的 shell 脚本时,我得到以下输出:
.
hello
如何打印 $RootDir
和 $message
的值?
有什么快捷方式可以导入配置文件而不是在 shell 脚本中写入 /home/s/project/Param/Param_File.config
吗?
试试这个:
#!/bin/ksh
. /home/s/project/Param/Param_File.config
current=$(dirname [=10=])
echo $current
echo 'hello'
echo $RootDir
echo $message
点(.
)告诉shell在当前环境中将文件作为脚本执行(因此环境更改有效)。参见例如here。您必须确保执行的文件是有效的脚本。
没有点 (.
) 脚本是 运行 在新进程中,不能改变它的父环境。
文档的相关部分:
. name [arg ...]
If name is a function defined with the function name
reserved word syntax, the function is executed in the current
environment (as if it had been defined with the name() syntax.)
Otherwise if name refers to a file, the file is read in its entirety
and the commands are executed in the current shell environment. The
search path specified by PATH is used to find the directory containing
the file. If any arguments arg are specified, they become the
positional parameters while processing the . command and the original
positional parameters are restored upon completion. Otherwise the
positional parameters are unchanged. The exit status is the exit
status of the last command executed.
我的 /home/s/project/bin/FileOperation.sh
文件是:
#!/bin/ksh
/home/s/project/Param/Param_File.config
current=$(dirname [=12=])
echo $current
echo 'hello'
echo $RootDir
echo $message
我的 /home/s/project/Param/Param_File.config
文件是:
RootDir=/home/s/project
message=hello
当我执行上面的 shell 脚本时,我得到以下输出:
.
hello
如何打印 $RootDir
和 $message
的值?
有什么快捷方式可以导入配置文件而不是在 shell 脚本中写入 /home/s/project/Param/Param_File.config
吗?
试试这个:
#!/bin/ksh
. /home/s/project/Param/Param_File.config
current=$(dirname [=10=])
echo $current
echo 'hello'
echo $RootDir
echo $message
点(.
)告诉shell在当前环境中将文件作为脚本执行(因此环境更改有效)。参见例如here。您必须确保执行的文件是有效的脚本。
没有点 (.
) 脚本是 运行 在新进程中,不能改变它的父环境。
文档的相关部分:
. name [arg ...]
If name is a function defined with the function name reserved word syntax, the function is executed in the current environment (as if it had been defined with the name() syntax.) Otherwise if name refers to a file, the file is read in its entirety and the commands are executed in the current shell environment. The search path specified by PATH is used to find the directory containing the file. If any arguments arg are specified, they become the positional parameters while processing the . command and the original positional parameters are restored upon completion. Otherwise the positional parameters are unchanged. The exit status is the exit status of the last command executed.