Shell脚本多个if else语句

时间:2020-06-24 11:30:51

标签: linux bash shell

这是代码,但我不知道该如何正确放置,因为它不是java或C#,所以我需要帮助..... 首先,我想创建一个文件夹(如果存在),然后转到文件夹并创建文件(如果文件已经存在),然后追加或替换文本,但是如果文件不存在,则创建一个文件夹,然后执行该操作;如果文件夹不存在,则创建一个文件夹然后添加文件并添加文本等等。

#! /bin/bash

echo "Enter folder name"
read folder
 
if [[ -d "$folder" ]]
then
        echo "Folder already Exits"     
        cd $folder
        echo "Now you are in your Folder named : $folder "
        echo "Enter file name"
        read file
        if [[ -f "$file" ]]
        then
                echo "File already exits"
                echo "Enter text you want to put in file"
                read fileText
                echo "$fileText" > $file
                echo "File text has been replaced with new text"
        else
                touch $file
                echo "File has been created"
                echo "Enter text you want to add"
                read FileText2
                echo "$FileText2" >> $file
        else
                mkdir $folder
                echo "You are inside folder"
                echo "Enter file name"
                read fileName
                echo "Enter text to append in file"
                read text
                echo "$fileName" >> $text
        fi
fi
 

2 个答案:

答案 0 :(得分:0)

您尚未完成find . -name '*.md' -type f -exec wc -w {} \; | awk '{ print $1 }' | sum 9658 2 的操作,因此else未与if [ -f "$file" ]配对。更改此:

if [ -d "$folder" ]

对此

    else
            mkdir $folder
            echo "You are inside folder"
            echo "Enter file name"
            read fileName
            echo "Enter text to append in file"
            read text
            echo "$fileName" >> $text
    fi
fi

答案 1 :(得分:-1)

#!/bin/bash
echo "Enter folder name"
read -r folder
if [[ -d "$folder" ]];then
echo "The folder already exists with name: $folder"
echo "Enter file name"
read -r file
cd "$folder" || exit
if [[ -f $file ]];then
echo "The file already exists with name: $file"
echo "Enter the text to append in $file"
read -r text
echo "$text" >> "$file"
else
touch "$file"
echo "File is created, Enter the text to append in $file"
read -r text
echo "$text" >> "$file"
fi
else
mkdir "$folder"
echo "New folder is created, Enter the filename"
read -r file
cd "$folder" || exit
touch "$file"
echo "Enter text to append in $file"
read -r text
echo "$text" >> "$file"
fi