Bash Script that Creates a File with a Variable in

2019-09-09 06:26发布

I am trying to write a variable into a file and also use the variable as the name of the file itself. Any ideas?

EXAMPLE 1: Filename and content within that file should be "helloworld"

#/bin/bash
OUTPUT="helloworld"
echo $OUTPUT > ~/Desktop/directory/outputs/$OUTPUT.txt

EXAMPLE 2: Filename and content within file should be "hellokitty"

#/bin/bash
OUTPUT="hellokitty"
echo $OUTPUT > ~/Desktop/directory/outputs/$OUTPUT.txt

标签: bash shell
2条回答
萌系小妹纸
2楼-- · 2019-09-09 06:52

This should work

#!/usr/bin/env bash

OUTPUT=hellokitty

echo "$OUTPUT" > ~/Desktop/directory/outputs/"${OUTPUT}".txt

You need to tell bash where your variable starts and where it ends. You can do this by using "${OUTPUT}" instead of just "$OUTPUT".

查看更多
再贱就再见
3楼-- · 2019-09-09 07:03

If you really want to do it that way, just use a 2-step, e.g.:

#!/bin/bash

output="helloword"
filename="$HOME/Desktop/directory/outputs/${output}".txt

echo "$output" > "$filename"
查看更多
登录 后发表回答