github.com/lmorg/murex@v0.0.0-20240217211045-e081c89cd4ef/docs/commands/tmp.md (about) 1 # `tmp` 2 3 > Create a temporary file and write to it 4 5 ## Description 6 7 `tmp` creates a temporary file, writes the contents of STDIN to it then returns 8 its filename to STDOUT. 9 10 You can optionally specify a file extension, for example if the temporary file 11 needs to be read by `open` or an editor which uses extensions to define syntax 12 highlighting. 13 14 ## Usage 15 16 ``` 17 <stdin> -> tmp [ file-extension ] -> <stdout> 18 ``` 19 20 ## Examples 21 22 ``` 23 » out "Hello, world!" -> set tmp 24 25 » out $tmp 26 /var/folders/3t/267q_b0j27d29bnf6pf7m7vm0000gn/T/murex838290600/8ec6936c1ac1c347bf85675eab4a0877-13893 27 28 » open $tmp 29 Hello, world! 30 ``` 31 32 ## Detail 33 34 The temporary file name is a base64 encoded md5 hash of the time plus Murex 35 function ID with Murex process ID appended: 36 37 ```go 38 package io 39 40 import ( 41 "crypto/md5" 42 "encoding/hex" 43 "io" 44 "os" 45 "strconv" 46 "time" 47 48 "github.com/lmorg/murex/lang" 49 "github.com/lmorg/murex/lang/types" 50 "github.com/lmorg/murex/utils/consts" 51 ) 52 53 func init() { 54 lang.DefineMethod("tmp", cmdTempFile, types.Any, types.String) 55 } 56 57 func cmdTempFile(p *lang.Process) error { 58 p.Stdout.SetDataType(types.String) 59 60 ext, _ := p.Parameters.String(0) 61 if ext != "" { 62 ext = "." + ext 63 } 64 65 fileId := time.Now().String() + ":" + strconv.Itoa(int(p.Id)) 66 67 h := md5.New() 68 _, err := h.Write([]byte(fileId)) 69 if err != nil { 70 return err 71 } 72 73 name := consts.TempDir + hex.EncodeToString(h.Sum(nil)) + "-" + strconv.Itoa(os.Getpid()) + ext 74 75 file, err := os.Create(name) 76 if err != nil { 77 return err 78 } 79 80 defer file.Close() 81 82 _, err = io.Copy(file, p.Stdin) 83 if err != nil { 84 return err 85 } 86 87 _, err = p.Stdout.Write([]byte(name)) 88 return err 89 } 90 ``` 91 92 This should should provide enough distance to run `tmp` in parallel....should 93 you ever want to. 94 95 `tmp` files are also located inside a unique per-process Murex temp directory 96 which itself is located in the appropriate temp directory for the host OS (eg 97 `$TMPDIR` on macOS). 98 99 ## See Also 100 101 * [`>>` Append File](../parser/greater-than-greater-than.md): 102 Writes STDIN to disk - appending contents if file already exists 103 * [`open`](../commands/open.md): 104 Open a file with a preferred handler 105 * [`pipe`](../commands/pipe.md): 106 Manage Murex named pipes 107 * [`|>` Truncate File](../parser/greater-than.md): 108 Writes STDIN to disk - overwriting contents if file already exists 109 110 <hr/> 111 112 This document was generated from [builtins/core/io/tmp_doc.yaml](https://github.com/lmorg/murex/blob/master/builtins/core/io/tmp_doc.yaml).