존재하지 않는 파일을 생성하는 쉘 스크립트? script successfully finishes. if [!

파일의 존재 여부를 확인하는 쉘 스크립트를 작성해야하며, 존재하지 않는 경우 파일을 작성하고 다음 명령으로 이동하거나 다음 명령으로 이동하십시오. 내가하지 않은 것은.

#!/bin/bash

# Check for the file that gets created when the script successfully finishes.
if [! -f /Scripts/file.txt]
then
: # Do nothing. Go to the next step?
else
mkdir /Scripts # file.txt will come at the end of the script
fi

# Next command (macOS preference setting)
defaults write ...

반품

line 5: [!: command not found
mkdir: /Scripts: File exists

어떻게해야할지 모르겠다. Google 검색에서 제공하는 모든 장소는 다른 것을 나타냅니다.



답변

아마도 더 간단한 해결책, 명시 적 테스트를 수행 할 필요가 없으며 다음을 사용하십시오.

mkdir -p /Scripts
touch /Scripts/file.txt

당신은 존재하는의 “수정”시간이 원하지 않는 경우 file.txt에 의해 변경 될 수를 touch, 당신이 사용할 수 touch -a /Scripts/file.txt있도록 touch단지 “접근”과 “변화”시간을 변경합니다.


답변

사이에 공백이 없기 때문에 오류를 얻고있다 [!그러나 코드에서 일부 결함도 있습니다. 먼저 파일이 존재하지 않는지 확인하고 그렇지 않은 경우 아무것도하지 않습니다. 파일이 존재하면 디렉토리를 작성하는 것입니다 (그러나 파일 작성을위한 조치는 수행하지 않음).

또한 null 연산이 필요하지 않으므로 간단하게 수행 할 수 있습니다.

#! /bin/bash -
if [[ ! -e /Scripts/file.txt ]]; then
    mkdir -p /Scripts
    touch /Scripts/file.txt
fi

[command2]

/Scripts/file.txt존재하지 않는지 확인하면 /Scripts디렉토리 가 생성 되고 file.txt파일 이 생성 됩니다. 원하는 경우 디렉토리의 존재 여부를 별도로 확인할 수도 있습니다. 또한 “일반 파일” http://tldp.org/LDP/abs/html/fto 인지 확인하는 위치에서 수행 할 파일의 존재 여부를 간단히 확인하도록 요청 하는 -e대신 사용 -f하고 있습니다 . html-e-f


답변

우선 쉘 스크립트bash script 가 아니므로 코드를 좀 더 일반적인 것으로 만들어 보자.

#!/bin/sh

모든 Posix 시스템에는 해당 파일이 있어야합니다. bash는 엄격하게 선택 사항입니다.

디렉토리가 존재하는지 테스트 할 필요가 없습니다.

dir=/Scripts
mkdir -p $dir

파일이없는 경우 파일을 만들려면

filename=$dir/file.txt
test -f $filename || touch $filename

또는 원하는 경우

filename=$dir/file.txt
if [ ! -f $filename ]
then
    touch $filename
fi

답변

구문 오류가 있습니다. 당신은 공간 전후에 필요 [하고 ].


답변

#!/bin/bash

# Check for the file that gets created when the script successfully finishes.
CHECKFILE="/Scripts/file.txt"

CHECKDIR=$( dirname "$CHECKFILE" )

# The directory with the file must exist
mkdir -p "$CHECKDIR"
if [ ! -f "$CHECKFILE" ]; then
    # What to do if the file is not there
fi
touch "$CHECKFILE"

상기는 이러한 생성과 같은 더 “속임수”가없는 것으로 간주 디렉토리 라고 /Scripts/file.txt( 항상 경우 분기를 입력에 스크립트를 강제의 방법이 될이). “file”이 디렉토리이면 -f 테스트가 실패하고 touch 명령이 변경되지 않습니다.


답변

내 접근 방식

#!/bin/sh

# input might contains spaces and other characters
FILEPATH="/tmp/some where/the file.blah"

# extract the file + dir names
FILE="`basename "${FILEPATH}"`"
DIR="`dirname "${FILEPATH}"`"

# create the dir, then the file
mkdir -p "${DIR}" && touch "${DIR}/${FILE}"

# show result
ls -l "$FILEPATH"

산출

  ./dofile.sh
  -rw-r--r-- 1 jmullee jmullee 0 Nov 15 21:23 /tmp/some where/the file.blah

.