【问题标题】:Unix command to make file and folders recursively [duplicate]Unix命令递归地制作文件和文件夹[重复]
【发布时间】:2022-03-11 11:54:07
【问题描述】:

我知道mkdir -p 会递归地创建目录。

我知道touch 会递归地创建一个文件。

我知道mkdir -p foo/bar; touch foo/bar/baz.txt 会起作用,但是touch 有标志或其他东西,所以我可以一步到位吗?

我确信这个问题已经被问过一百万次了,但由于某种原因,我的回答是空的。

【问题讨论】:

  • touch 没有允许这样做的选项。但是,您可以编写一个结合这两个调用的 shell 函数。祝你好运。
  • 假设你正在做的已经是一步。否则搜索“make_path in linux”
  • 呃,它不是 DRY 真可惜,但没有它我活了这么久。 make_path 不附带 bash 并且看起来更像是一个 Perl 函数,所以我可能会不使用它。感谢大家。 =)

标签: bash shell unix


【解决方案1】:

别名或函数呢:

function my_touch {
  mkdir -p $(dirname $1) && touch $1
}

my_touch /tmp/a/b/aaa ; ls -l /tmp/a/b/aaa

【讨论】:

    【解决方案2】:
    function mytouch { for x in "$@"; do mkdir -p -- `dirname -- "$item"` && touch -- "$x"; done }
    

    用法:

    mytouch aa/bb/cc/dd.txt --a/b/c/d.txt -a/b/c/d.txt
    
    $ ls -- aa/bb/cc/dd.txt --a/b/c/d.txt -a/b/c/d.txt                                                    
    --a/b/c/d.txt   -a/b/c/d.txt    aa/bb/cc/dd.txt
    

    【讨论】:

    • 你在这里做得不好:有很多引号丢失。此外,如果调用为 mytouch -hello,这将不起作用。即使您修复了所有引号,由于dir=$(dirname "$1"),您将无法在dir 中添加尾随换行符,例如mytouch $'a/b/c\n/d
    • pluse-uno 表示“做一件事并做好”,因为看起来 O.P. 并没有吸收 unix/linux 哲学的关键点,但我认为 gniourf_gniourf 有一些有效的 cmets .祝大家好运。
    【解决方案3】:

    install 的 GNU 实现可以做到这一点:

    install -D /dev/null foo/bar/baz.txt
    # will create an empty baz.txt file in foo/bar
    

    如果您使用没有coreutils 的 OS X,您必须使用已经建议的函数

    【讨论】:

    • 不错的选择。你能检查一下是否会通过上面@gniourf_gniourf 评论中的mytouch $'a/b/c\n/d 测试。祝大家好运。
    猜你喜欢
    • 1970-01-01
    • 2018-11-28
    • 2014-08-11
    • 1970-01-01
    • 2014-02-07
    • 1970-01-01
    • 2015-12-04
    • 2019-11-04
    • 2019-07-02
    相关资源
    最近更新 更多