简体   繁体   English

从bash中的文件读取并执行带有空格的行

[英]Read and execute lines with spaces from file in bash

I'm facing a problem in a bash shell script when I try to read some lines from a file and execute them one by one. 当我尝试从文件中读取一些行并逐行执行它们时,我在bash shell脚本中遇到了问题。 The problem occurs when the line has an argument with spaces. 当行的参数中带有空格时,就会发生此问题。 Code: 码:

while read i
do
   $i
done < /usr/bin/tasks

tasks file: 任务文件:

mkdir Hello\ World
mkdir "Test Directory"

Both of the above instructions work perfectly when executed directly from the terminal, creating only two directories called "Hello World" and "Test Directory" respectively, but the same doesn't happen when the instructions are read and executed from the script, meaning that four directories are created. 当直接从终端执行时,上述两个指令都可以完美工作,分别仅创建两个目录“ Hello World”和“ Test Directory”,但是从脚本读取和执行指令时不会发生相同的情况,这意味着将创建四个目录。

Having said that, I would like to keep my code as simple as possible and, if possible, I'd prefer not to use the cat command. 话虽如此,我想使我的代码尽可能简单,并且,如果可能的话,我不想使用cat命令。 Thanks in advance for any help. 在此先感谢您的帮助。

As simple as possible? 尽可能简单? You are re-implementing the . 您正在重新实现. (or source , as bash allows you to spell it) command: (或source ,因为bash允许您拼写)命令:

. /usr/bin/tasks

or 要么

source /usr/bin/tasks

To execute one line at a time, use eval . 要一次执行一行,请使用eval

while IFS= read -r i; do
    eval "$i"
done

This assumes that each line of the file contains one or more complete commands that can be executed individually. 假定文件的每一行都包含一个或多个可以单独执行的完整命令。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM